forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT2.java
More file actions
56 lines (52 loc) · 1.11 KB
/
T2.java
File metadata and controls
56 lines (52 loc) · 1.11 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* @program JavaBooks
* @description: 链表中倒数第k个节点
* @author: mf
* @create: 2020/03/06 20:55
*/
package subject.linked;
import java.util.Stack;
/**
* 1->2->3->4->5 k = 2
* 返回:
* 4->5
*/
public class T2 {
/**
* 栈,比较容易想得的到
* @param head
* @param k
* @return
*/
public ListNode getKthFromEnd(ListNode head, int k) {
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
ListNode listNode= new ListNode(0);
for (int i = 0; i < k; i++) {
listNode = stack.pop();
}
return listNode;
}
/**
* 双指针
* @param head
* @param k
* @return
*/
public ListNode getKthFromEnd2(ListNode head, int k) {
ListNode pNode = head;
ListNode kNode = head;
int p1 = 0;
while (pNode != null) {
if (p1 >= k) {
kNode = kNode.next;
}
pNode = pNode.next;
p1++;
}
return kNode;
}
}