题目地址:
https://www.lintcode.com/problem/nth-to-last-node-in-list/description
给定一个链表,求其倒数第 n n n个节点。题目保证 n n n是合法的。
快慢指针,快指针先走 n n n步然后慢指针快指针一起走。代码如下:
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;
}
}
时间复杂度 O ( l ) O(l) O(l), l l l为链表长度,空间 O ( 1 ) O(1) O(1)。