-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSolution.java
60 lines (54 loc) · 1.53 KB
/
Solution.java
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
package ds.pointer.targetoffer22;
/**
* 链表中倒数第k个节点
* LeetCode 剑指offer 22 https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
*
* @author yangyi 2022年04月24日17:50:02
*/
public class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
/**
* 1->2->3->4->5, 和 k = 2.
*/
private ListNode createLink() {
ListNode node_1 = new ListNode(1);
ListNode node_2 = new ListNode(2);
ListNode node_3 = new ListNode(3);
ListNode node_4 = new ListNode(4);
ListNode node_5 = new ListNode(5);
node_1.next = node_2;
node_2.next = node_3;
node_3.next = node_4;
node_4.next = node_5;
return node_1;
}
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
while (k != 0) {
fast = fast.next;
k--;
}
while (true) {
if (fast == null) {
break;
}
fast = fast.next;
slow = slow.next;
}
return slow;
}
public static void main(String[] args) {
Solution getKthFromEnd = new Solution();
ListNode link = getKthFromEnd.createLink();
int k = 2;
ListNode result = getKthFromEnd.getKthFromEnd(link, k);
System.out.println("1->2->3->4->5链表中的倒数第" + k + "个节点为: " + result.val);
}
}