File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments