https://leetcode.com/problems/remove-nth-node-from-end-of-list/

★☆☆☆☆

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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
if (!head.next && n === 1) {
head = null
return head
}
let p = head
let l = 1
while (p.next) {
l++
p = p.next
}
if (l === n) {
head = head.next
return head
}
p = head
let i = 1
while (p.next) {
if (l - n === i) {
p.next = p.next.next
break
}
i++
p = p.next
}
return head
}

★★★☆☆☆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
int length = 0;
ListNode first = head;
while (first != null) {
length++;
first = first.next;
}
length -= n;
first = dummy;
while (length > 0) {
length--;
first = first.next;
}
first.next = first.next.next;
return dummy.next;
}

★★★★★
这个操作太秀了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var removeNthFromEnd = function(head, n) {
const dummy = new ListNode()
dummy.next = head
let fast = dummy
let slow = dummy
while (fast && n >= 0) {
fast = fast.next
n--
}
while (fast) {
fast = fast.next
slow = slow.next
}
slow.next = slow.next.next
return dummy.next
}