-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_256.js
More file actions
67 lines (56 loc) Β· 1.12 KB
/
problem_256.js
File metadata and controls
67 lines (56 loc) Β· 1.12 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
/**
* Definition for singly-linked list.
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* Rearrange linkedlist in alternating order
* @param {ListNode} head
*/
function reorderList(head) {
if (!head || !head.next) return head;
let prev = head;
let tail = head.next;
while (tail) {
tail.prev = prev;
prev = tail;
tail = tail.next;
}
let cur = head;
while (cur !== prev && cur.prev !== prev) {
const { next } = cur;
cur.next = prev;
prev.next = next;
prev = prev.prev;
cur = next;
}
cur.next = null;
return head;
}
/**
* Print LinkedList in arrow form
* @param {ListNode} head
*/
const printList = head => {
let current = head;
const arr = [];
while (current !== null) {
arr.push(current.val);
current = current.next;
}
console.log(arr.join(' -> '));
};
const a = new ListNode(1);
const b = new ListNode(2);
const c = new ListNode(3);
const d = new ListNode(4);
const e = new ListNode(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
printList(a); // 1 -> 2 -> 3 -> 4 -> 5
reorderList(a);
printList(a); // 1 -> 5 -> 2 -> 4 -> 3