forked from zfman/AlgorithmCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindKthToTailSolution.java
More file actions
42 lines (37 loc) · 1.05 KB
/
Copy pathFindKthToTailSolution.java
File metadata and controls
42 lines (37 loc) · 1.05 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
package offer;
import leetcode.common.LinkedUtils;
import leetcode.common.ListNode;
/**
* 链表中倒数第k个结点
*
* 输入一个链表,输出该链表中倒数第k个结点。
*
* @author 刘壮飞
* https://github.com/zfman.
* https://blog.csdn.net/lzhuangfei.
*/
public class FindKthToTailSolution {
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null || k <= 0) return null;
ListNode fast = head;
ListNode low = head;
for (int i = 1; i < k; i++) {
if (fast.next != null) {
fast = fast.next;
} else return null;
}
while (fast.next != null) {
fast = fast.next;
low = low.next;
}
return low;
}
public static void main(String[] args) {
int[] array = {
1
};
ListNode node = LinkedUtils.arrayToLinkedList(array);
ListNode r = new FindKthToTailSolution().FindKthToTail(node, 1);
System.out.println(r == null ? "root is null" : r.val);
}
}