forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT14.java
More file actions
63 lines (60 loc) · 1.35 KB
/
T14.java
File metadata and controls
63 lines (60 loc) · 1.35 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
57
58
59
60
61
62
63
package web; /**
* @program LeetNiu
* @description: 链表中倒数第k个结点
* @author: mf
* @create: 2020/01/10 15:11
*/
import java.util.Stack;
/**
* 输入一个链表,输出该链表中倒数第k个结点。
*/
public class T14 {
/**
* 双指针
* @param head
* @param k
* @return
*/
public ListNode FindKthToTail(ListNode head,int k) {
// 判断
if (head == null || k <= 0) return null;
ListNode pNode = head;
ListNode kNode = head;
int p1 = 0;
while (pNode != null) {
if (p1 > k - 1){
kNode = kNode.next;
}
pNode = pNode.next;
p1++;
}
if (p1 >= k) {
return kNode;
}
return null;
}
/**
* 栈
* @param head
* @param k
* @return
*/
public ListNode FindKthToTail2(ListNode head,int k) {
// 判断
if (head == null || k <= 0) return null;
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
int temp = 0;
while (!stack.empty()) {
ListNode listNode = stack.pop();
temp++;
if (temp == k) {
return listNode;
}
}
return null;
}
}