-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode19.java
More file actions
60 lines (54 loc) · 1.8 KB
/
LeetCode19.java
File metadata and controls
60 lines (54 loc) · 1.8 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
import util.ListNode;
import util.PrintUtil;
public class LeetCode19 {
public static void main(String[] args) {
ListNode head;
// 输入:head = [1,2,3,4,5], n = 2
// 输出:[1,2,3,5]
head = ListNode.buildLinkedList(new Integer[] { 1, 2, 3, 4, 5 });
System.out.println(head);
head = new Solution19().removeNthFromEnd(head, 2);
System.out.println(head);
PrintUtil.printDivider();
// 输入:head = [1], n = 1
// 输出:[]
head = new ListNode(1);
System.out.println(head);
head = new Solution19().removeNthFromEnd(head, 1);
System.out.println(head);
PrintUtil.printDivider();
// 输入:head = [1,2], n = 1
// 输出:[1]
head = ListNode.buildLinkedList(new Integer[] { 1, 2 });
System.out.println(head);
head = new Solution19().removeNthFromEnd(head, 1);
System.out.println(head);
PrintUtil.printDivider();
// 输入:head = [1,2], n = 2
// 输出:[2]
head = ListNode.buildLinkedList(new Integer[] { 1, 2 });
System.out.println(head);
head = new Solution19().removeNthFromEnd(head, 2);
System.out.println(head);
PrintUtil.printDivider();
}
}
class Solution19 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode slowNode = head;
ListNode fastNode = head;
for (int i = 0; i < n; i++) {
fastNode = fastNode.next;
}
if (fastNode == null) {
head = head.next;
return head;
}
while (fastNode != null && fastNode.next != null) {
fastNode = fastNode.next;
slowNode = slowNode.next;
}
slowNode.next = slowNode.next.next;
return head;
}
}