Skip to content

Commit 356b9de

Browse files
committed
Add reverse-linked-list solution
1 parent ec041f9 commit 356b9de

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

reverse-linked-list/Jeehay28.js

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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 {ListNode}
11+
*/
12+
13+
// Time Complexity: O(n)
14+
// Space Complexity: O(1)
15+
16+
// The algorithm uses a constant amount of extra space: prev, current, and nextTemp.
17+
// No additional data structures (like arrays or new linked lists) are created.
18+
// Hence, the space complexity is O(1).
19+
20+
var reverseList = function (head) {
21+
let prev = null;
22+
let current = head;
23+
24+
while (current) {
25+
let nextTemp = current.next;
26+
27+
current.next = prev;
28+
console.log(current, prev);
29+
30+
prev = current;
31+
console.log(current, prev);
32+
current = nextTemp;
33+
}
34+
35+
return prev; // New head of the reversed list
36+
};
37+
38+
// head = [1,2,3,4,5]
39+
// [1] null
40+
// [1] [1]
41+
// [2,1] [1]
42+
// [2,1] [2,1]
43+
// [3,2,1] [2,1]
44+
// [3,2,1] [3,2,1]
45+
// [4,3,2,1] [3,2,1]
46+
// [4,3,2,1] [4,3,2,1]
47+
// [5,4,3,2,1] [5,4,3,2,1]
48+
49+
// my own approach
50+
// Time Complexity: O(n)
51+
// Space Complexity: O(n)
52+
var reverseList = function (head) {
53+
if (head === null) {
54+
return null;
55+
}
56+
57+
let current = head;
58+
let arr = [];
59+
// console.log(head.val)
60+
61+
// traverse the linked List - TC: O(n)
62+
while (current) {
63+
arr.push(current.val);
64+
current = current.next;
65+
}
66+
67+
// reverse the array - TC: O(n)
68+
arr = arr.reverse();
69+
70+
let head1 = new ListNode(arr[0]);
71+
let current1 = head1;
72+
73+
// rebuild the linked list - TC: O(n)
74+
for (let i = 1; i < arr.length; i++) {
75+
current1.next = new ListNode(arr[i]);
76+
current1 = current1.next;
77+
}
78+
79+
return head1;
80+
};
81+
82+

0 commit comments

Comments
 (0)