Skip to content

Commit 0a32dba

Browse files
authored
Create 143-Reorder-List.js
1 parent a09d41d commit 0a32dba

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

javascript/143-Reorder-List.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {void} Do not return anything, modify head in-place instead.
11+
*/
12+
var reorderList = function(head) {
13+
if (!head) { return };
14+
15+
let slow = head;
16+
let fast = head;
17+
18+
19+
// finding the middle of the linked list using 2 pters
20+
while (fast && fast.next) {
21+
slow = slow.next;
22+
fast = fast.next.next;
23+
}
24+
25+
// reverse the second part of the list starting at slow
26+
let prev = null
27+
let curr = slow;
28+
while (curr) {
29+
let next = curr.next;
30+
curr.next = prev;
31+
prev = curr;
32+
curr = next;
33+
} // here prev is the head
34+
35+
// merge two sorted lists (first one starts at head, second at prev)
36+
let first = head;
37+
let second = prev;
38+
39+
while(second.next) {
40+
temp = first.next;
41+
first.next = second;
42+
first = temp;
43+
44+
temp = second.next;
45+
second.next = first;
46+
second = temp;
47+
}
48+
49+
50+
};

0 commit comments

Comments
 (0)