Offer.P22[链表中倒数第k个节点]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode p = head;
int n = 0;
while (p != null) {
++n;
p = p.next;
}
p = head;
for (int i = 1; i <= n - k; ++i) {
p = p.next;
}
return p;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

方法二:双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode slow = head, fast = head;
while (k-- > 0) {
fast = fast.next;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$