題目地址:
https://www.lintcode.com/problem/nth-to-last-node-in-list/description
給定一個鏈表,求其倒數第個節點。題目保證是合法的。
快慢指針,快指針先走步然後慢指針快指針一起走。代碼如下:
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.
*/
public ListNode nthToLast(ListNode head, int n) {
// write your code here
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
時間複雜度,爲鏈表長度,空間。