forked from lcl1026504480/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
43 lines (39 loc) · 867 Bytes
/
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
/**
* @author Anonymous
* @since 2019/11/21
*/
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
/**
* 找出链表倒数第k个节点,k从1开始
* @param head 链表头部
* @param k 第k个节点
* @return 倒数第k个节点
*/
public ListNode FindKthToTail(ListNode head,int k) {
if (head == null || k < 1) {
return null;
}
ListNode pre = head;
for (int i = 0; i < k - 1; ++i) {
if (pre.next != null) {
pre = pre.next;
} else {
return null;
}
}
ListNode cur = head;
while (pre.next != null) {
pre = pre.next;
cur = cur.next;
}
return cur;
}
}