Skip to content

Commit b23d809

Browse files
authored
Create linked_list_reverse.js
1 parent 0e27bb0 commit b23d809

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Linked List/linked_list_reverse.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//Problem statement-Given the head of a singly linked list, reverse the list, and return the reversed list.
2+
3+
// Iteratively
4+
* @param {ListNode} head
5+
* @return {ListNode}
6+
*/
7+
var reverseList = function(head) {
8+
// Handling the edge cases if head node is null or when single node is there
9+
if (head === null || head.next === null) {
10+
return head;
11+
}
12+
// Using three pointer approach
13+
let prev = null;
14+
let curr = head;
15+
let fwd = null;
16+
while (curr !== null) {
17+
// Updatng the value of each of the pointers
18+
fwd = curr.next;
19+
curr.next = prev;
20+
prev = curr;
21+
curr = fwd;
22+
}
23+
// Returning the head of the reversed linked list
24+
return prev;
25+
};
26+
27+
// Recursively
28+
var reverseList = function(head) {
29+
// Base case- If the head is null or single node is there
30+
if (head === null || head.next === null) {
31+
return head;
32+
}
33+
34+
// Recursively reverse the remaining list starting from the next node
35+
const reversedList = reverseList(head.next);
36+
37+
// Reversing the links between the current and next node
38+
head.next.next = head;
39+
head.next = null;
40+
41+
// Returning the head of the reversed linked list
42+
return reversedList;
43+
};

0 commit comments

Comments
 (0)