File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity: O(n)
2+ // Space complexity: O(n)
3+
4+ /**
5+ * Definition for singly-linked list.
6+ * function ListNode(val, next) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.next = (next===undefined ? null : next)
9+ * }
10+ */
11+ /**
12+ * @param {ListNode } head
13+ * @return {ListNode }
14+ */
15+ var reverseList = function ( head ) {
16+ const stack = [ ] ;
17+
18+ let temp = head ;
19+ while ( temp ) {
20+ stack . push ( temp . val ) ;
21+ temp = temp . next ;
22+ }
23+
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 ;
40+ } ;
You can’t perform that action at this time.
0 commit comments