-
Notifications
You must be signed in to change notification settings - Fork 20
/
ReverseLinkedListII.js
103 lines (90 loc) · 2.32 KB
/
ReverseLinkedListII.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
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
/**
* Reverse a linked list from position m to n. Do it in-place and in one-pass.
*
* For example:
* Given 1->2->3->4->5->NULL, m = 2 and n = 4,
*
* return 1->4->3->2->5->NULL.
*
* Note:
* Given m, n satisfy the following condition:
* 1 ≤ m ≤ n ≤ length of list.
*
* Accepted.
*/
function ListNode(val) {
this.val = val;
this.next = null;
this.equals = function (node) {
return this.next == null && node.next == null || this.val === node.val && (this.next != null) && this.next.equals(node.next);
}
}
/**
* @param {ListNode} head
* @param {number} m
* @param {number} n
* @return {ListNode}
*/
let reverseBetween = function (head, m, n) {
let node = head;
let list = [];
for (let i = 0; i <= n - 1 && node != null; i++) {
if (m - 1 <= i) {
list.push(node);
}
node = node.next;
}
while (list.length >= 2) {
let tmp = list[0].val;
list[0].val = list[list.length - 1].val;
list[list.length - 1].val = tmp;
list.splice(0, 1);
list.splice(list.length - 1, 1);
}
return head;
};
if (reverseBetween(null, 1, 2) === null) {
console.log("pass")
} else {
console.error("failed")
}
let node123 = new ListNode(1);
node123.next = new ListNode(2);
node123.next.next = new ListNode(3);
let tmp = new ListNode(1);
tmp.next = new ListNode(3);
tmp.next.next = new ListNode(2);
if (reverseBetween(node123, 2, 3).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}
if (reverseBetween(new ListNode(1), 1, 1).equals(new ListNode(1))) {
console.log("pass")
} else {
console.error("failed")
}
let node12 = new ListNode(1);
node12.next = new ListNode(2);
tmp = new ListNode(2);
tmp.next = new ListNode(1);
if (reverseBetween(node12, 1, 2).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}
let node12345 = new ListNode(1);
node12345.next = new ListNode(2);
node12345.next.next = new ListNode(3);
node12345.next.next.next = new ListNode(4);
node12345.next.next.next.next = new ListNode(5);
tmp = new ListNode(1);
tmp.next = new ListNode(4);
tmp.next.next = new ListNode(3);
tmp.next.next.next = new ListNode(2);
tmp.next.next.next.next = new ListNode(5);
if (reverseBetween(node12345, 2, 4).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}