-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19.js
52 lines (50 loc) · 967 Bytes
/
19.js
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
/**
* 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) {
// 双指针
// 首指针先走n个
let first = head;
let second;
while (n > 0) {
first = first.next;
n--;
}
second = head;
if (first == null) {
return head.next;
}
while (first.next !== null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return head;
};
function creatList(array) {
let head;
array.reduce((pre, curr) => {
let node = {
val: curr,
next: null
};
if (pre === null) {
head = node;
} else {
pre.next = node;
}
return node;
}, null);
return head;
}
console.log(removeNthFromEnd(creatList([1, 2, 3, 4, 5]), 2));
debugger;