Nth to Last Node in List

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 }

 

posted @ 2016-03-26 09:12  YuriFLAG  阅读(195)  评论(0)    收藏  举报