码迷,mamicode.com
首页 > 其他好文 > 详细

Nth to Last Node in List

时间:2016-03-26 10:48:09      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Find the nth to last element of a singly linked list. 

The minimum number of nodes in list is n.

Example

Given a List  3->2->1->5->null and n = 2, return node  whose value is 1.

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param head: The first node of linked list.
15      * @param n: An integer.
16      * @return: Nth to last node of a singly linked list. 
17      */
18     ListNode nthToLast(ListNode head, int n) {
19         if (head == null) {
20             return null;
21         }
22         ListNode front = head;
23         ListNode node = head;
24         while (n > 0) {
25             if (front == null) {
26                 return null;
27             }
28             front = front.next;
29             n--;
30         }
31         while (front != null) {
32             node = node.next;
33             front = front.next;
34         }
35         return node;
36     }
37 }

 

Nth to Last Node in List

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5321958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!