Nth to Last Node in List

来源:互联网 发布:matlab 矩阵元素赋值 编辑:程序博客网 时间:2024/05/19 12:25

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.

快慢指针,让快指针先走n - 1次,然后快慢指针一起走,当fast == null 的时候,说明slow的位置就是所求的结果。


代码:

ListNode nthToLast(ListNode head, int n) {        // write your code here        if(head == null) return null;        ListNode fast = head;        ListNode slow = head;        int count = 1;        while(count<n && fast.next != null)        {            fast = fast.next;            count++;        }        while(fast.next != null){            slow = slow.next;            fast = fast.next;        }        return slow;    }


0 0