[lintcode easy]Nth to Last Node in List

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.

 

////use two pointer to record the node, one is n step faster than slow pointer

///so when fast meet the end, slow is the last Nth node.

 

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: Nth to last node of a singly linked list. 
     */
    ListNode nthToLast(ListNode head, int n) {
        // write your code here
        if(head==null || n<0 ) return head;
        ListNode slow=head;
        ListNode fast=head;

        while(n-- !=0)
        {
            fast=fast.next;
        }
        while(fast !=null)
        {
            fast=fast.next;
            slow=slow.next;
        }
        
        return slow;
    }
}

 

posted on 2015-11-24 15:05  一心一念  阅读(146)  评论(0编辑  收藏  举报

导航