链表中倒数第k个节点

输入一个链表,输出该链表中倒数第k个结点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (k <= 0) {
return null;
}
Stack<ListNode> stack = new Stack();
ListNode point = head;
while (null != point){
stack.push(point);
point = point.next;
}
if (k > stack.size()){
return null;
}
while(0 != k--){
point = stack.pop();
}
return point;
}
}

上面的解决方案空间复杂度是o(n),时间复杂度o(n+k);下面的解决方案更好,空间复杂度是o(1),时间复杂度是o(n);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (k <= 0) {
return null;
}
ListNode refrence = head;
ListNode point = null;
int i = 1;
while (null != refrence) {
if (i == k) {
point = head;
} else if (i > k){
point = point.next;
}
refrence = refrence.next;
i++;
}
return point;
}
}