File tree 1 file changed +9
-22
lines changed
1 file changed +9
-22
lines changed Original file line number Diff line number Diff line change 1
1
// Time complexity: O(n)
2
- // Space complexity: O(n )
2
+ // Space complexity: O(1 )
3
3
4
4
/**
5
5
* Definition for singly-linked list.
13
13
* @return {ListNode }
14
14
*/
15
15
var reverseList = function ( head ) {
16
- const stack = [ ] ;
16
+ let current = head ;
17
+ let prev = null ;
17
18
18
- let temp = head ;
19
- while ( temp ) {
20
- stack . push ( temp . val ) ;
21
- temp = temp . next ;
19
+ while ( current ) {
20
+ const node = new ListNode ( current . val ) ;
21
+ node . next = prev ;
22
+ prev = node ;
23
+ current = current . next ;
22
24
}
23
25
24
- if ( ! stack . length ) {
25
- return null ;
26
- }
27
-
28
- const popped = stack . pop ( ) ;
29
- const answer = new ListNode ( popped ) ;
30
-
31
- temp = answer ;
32
- while ( stack . length > 0 ) {
33
- const popped = stack . pop ( ) ;
34
-
35
- temp . next = new ListNode ( popped ) ;
36
- temp = temp . next ;
37
- }
38
-
39
- return answer ;
26
+ return prev ;
40
27
} ;
You can’t perform that action at this time.
0 commit comments