You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: 143/my_solution.js
+105-69
Original file line number
Diff line number
Diff line change
@@ -19,99 +19,135 @@ class ListNode {
19
19
* @return {void} Do not return anything, modify head in-place instead.
20
20
*/
21
21
constreorderList=(head)=>{
22
-
// let slow = head, fast = head.next;//, reversed = new ListNode(), dummy = new ListNode(), result = dummy;
23
-
// while (fast && fast.next) {
24
-
// slow = slow.next
25
-
// fast = fast.next.next;
26
-
// }
22
+
letslow=head,fast=head.next;
23
+
24
+
while(fast&&fast.next){
25
+
slow=slow.next;
26
+
fast=fast.next.next;
27
+
}
28
+
29
+
/*
30
+
31
+
In the provided code, the original implementation splits the linked list into two halves by setting the slow.next pointer to null. This is done to separate the first half (head to slow) from the second half (slow.next to the end).
32
+
33
+
The reason for setting slow.next = null is to disconnect the two halves so that the second half can be reversed independently. This ensures that the first half doesn't have any reference to the reversed second half. It simplifies the merging step later.
34
+
35
+
In your suggested code, you're attempting to reverse the second half while keeping the reference to the first half intact. While it's possible to reverse the second half this way, it would make the merging step more complex since you'd need to traverse both the first and reversed second halves simultaneously to interleave the nodes.
36
+
37
+
*/
38
+
// // MY REVERSE: -- DOES NOT WORK
39
+
// slow = slow.next; // Shift from [2,3,4] -> [3,4] in order to reverse as full LL -> [1,2,3,4]
40
+
// console.log("-> slow")
41
+
// console.log(slow)
27
42
//
28
-
// console.log("slow")
29
-
// console.log(slow)
30
-
// console.log("fast")
31
-
// console.log(fast)
43
+
// let part2 = new ListNode(); // reversed
44
+
// while (slow) {
45
+
// part2.next = new ListNode(slow.val, part2.next)
46
+
// slow = slow.next;
47
+
// }
48
+
// part2 = part2.next;
49
+
// // Reversed
50
+
// console.log("---> Reversed -> part2")
51
+
// console.log(part2)
52
+
// console.log("_____________________________")
53
+
// let part1 = head;
54
+
55
+
// ONLINE:
56
+
letsecondHalf=slow.next;
57
+
slow.next=null;// This is the magical part that breaks the links
0 commit comments