Lintcode: Nth to Last Node in List

时间:2023-12-22 16:59:02
Find the nth to last element of a singly linked list. 

The minimum number of nodes in list is n.

Example
Given a List ->->->->null and n = , return node whose value is .

Runner Technique: 两个指针都从Dummy node出发,结束条件是runner.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
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode walker = dummy;
ListNode runner = dummy;
while (runner.next != null && n>0) {
runner = runner.next;
n--;
}
while (runner.next != null) {
runner = runner.next;
walker = walker.next;
}
return walker.next;
}
}