-
Notifications
You must be signed in to change notification settings - Fork 6
/
KthNodeFromTheEndOfLinkedList.java
111 lines (105 loc) · 2.59 KB
/
KthNodeFromTheEndOfLinkedList.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package io.ziheng.codinginterviews;
import java.util.LinkedList;
import java.util.List;
/**
* 单链表节点
*/
class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* 剑指 Offer 面试题 22:链表倒数第 k 个节点
*
* 题目描述:
* 输入一个链表,输出该链表中倒数第 k 个节点。
*
* 知识点:["链表"]
*/
public class KthNodeFromTheEndOfLinkedList {
/**
* 主函数 -> 测试用例
*
* @param args
* @return void
*/
public static void main(String[] args) {
KthNodeFromTheEndOfLinkedList obj = new KthNodeFromTheEndOfLinkedList();
int[] arr = new int[]{1, 2, 3, 4, 5, };
ListNode head = buildList(arr);
System.out.println(
printList(head)
);
ListNode node = obj.findKthNodeFromTheEnd(head, 5);
System.out.println(
node == null ? node : node.val
);
}
/**
* 单向链表转列表
*
* @param head
* @return ListNode
*/
public static List<Integer> printList(ListNode head) {
List<Integer> resultList = new LinkedList<>();
ListNode currentNode = head;
while (currentNode != null) {
resultList.add(currentNode.val);
currentNode = currentNode.next;
}
return resultList;
}
/**
* 快速构建单向链表
*
* @param arr
* @return ListNode
*/
public static ListNode buildList(int[] arr) {
ListNode dummyhead = new ListNode(0);
ListNode currentNode = dummyhead;
for (int n : arr) {
ListNode node = new ListNode(n);
currentNode.next = node;
currentNode = currentNode.next;
}
return dummyhead.next;
}
/**
* 剑指 Offer 面试题 22:链表倒数第 k 个节点
*
* @param head
* @param k
* @return ListNode
*/
public ListNode findKthNodeFromTheEnd(ListNode head, int k) {
// 处理异常情况
if (head == null || k < 0) {
return null;
}
ListNode pA = head;
ListNode pB = head;
for (int i = 0; i < k; i++) {
// k 越界
if (pA == null) {
return null;
}
pA = pA.next;
}
while (pA != null) {
pA = pA.next;
pB = pB.next;
}
return pB;
}
}
/* EOF */