-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthNodeFromEndOfList.java
More file actions
67 lines (63 loc) · 1.79 KB
/
RemoveNthNodeFromEndOfList.java
File metadata and controls
67 lines (63 loc) · 1.79 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
61
62
63
64
65
66
67
package com.cier.solution.list;
import com.cier.solution.common.ListNode;
/**
* https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/
*/
public class RemoveNthNodeFromEndOfList {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
public ListNode removeNthFromEnd2(ListNode head, int n) {
// cnt 是链表的长度
int cnt = 0;
ListNode temp = head;
while (temp != null) {
cnt++;
temp = temp.next;
}
// 算出从后数 n 个从前数第几个
cnt = cnt - n;
if (cnt == 0) {
return head.next;
} else {
temp = head;
// head 已经是第一个了,所以 cnt 减一
cnt--;
while (cnt-- != 0) {
temp = temp.next;
}
temp.next = temp.next.next;
return head;
}
}
public ListNode removeNthFromEnd3(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
int count = 0;
while (fast.next != null) {
if (count < n) {
count++;
fast = fast.next;
} else {
fast = fast.next;
slow = slow.next;
}
}
slow.next = slow.next.next;
return dummy.next;
}
}