Skip to content

Commit 05d1725

Browse files
committed
solve: reorder list
1 parent 14ef09a commit 05d1725

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

reorder-list/evan.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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+
const middleNode = findMiddleNode(head);
14+
let reversedHalf = reverseList(middleNode.next);
15+
middleNode.next = null;
16+
17+
let half = head;
18+
19+
while (reversedHalf) {
20+
const nextForward = half.next;
21+
const nextBackward = reversedHalf.next;
22+
23+
half.next = reversedHalf;
24+
reversedHalf.next = nextForward;
25+
26+
reversedHalf = nextBackward;
27+
half = nextForward;
28+
}
29+
};
30+
/**
31+
* Time Complexity: O(n)
32+
* - Finding the middle node takes O(n).
33+
* - Reversing the second half takes O(n).
34+
* - Merging the two halves takes O(n).
35+
* - Overall, the time complexity is O(n) + O(n) + O(n) = O(n).
36+
*
37+
* Space Complexity: O(1)
38+
* - We only use a constant amount of extra space (pointers),
39+
* so the space complexity is O(1).
40+
*/
41+
42+
/**
43+
* @param {ListNode} head
44+
* @return {ListNode}
45+
*/
46+
var reverseList = function (head) {
47+
let currentNode = head;
48+
let previousNode = null;
49+
50+
while (currentNode !== null) {
51+
const nextNode = currentNode.next;
52+
53+
currentNode.next = previousNode;
54+
previousNode = currentNode;
55+
currentNode = nextNode;
56+
}
57+
58+
return previousNode;
59+
};
60+
61+
/**
62+
* @param {ListNode} head
63+
* @return {ListNode}
64+
*/
65+
var findMiddleNode = function (head) {
66+
if (!head) return null;
67+
68+
let slow = head;
69+
let fast = head;
70+
71+
while (fast !== null && fast.next !== null) {
72+
slow = slow.next;
73+
fast = fast.next.next;
74+
}
75+
76+
return slow;
77+
};

0 commit comments

Comments
 (0)