File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/reverse-linked-list/
3
+ * 풀이방법: 스택을 사용하여 역순으로 노드를 생성
4
+ *
5
+ * 시간복잡도: O(n) (n: 리스트의 길이)
6
+ * 공간복잡도: O(n) (스택에 모든 노드를 저장)
7
+ */
8
+
9
+ /**
10
+ * Definition for singly-linked list.
11
+ * class ListNode {
12
+ * val: number
13
+ * next: ListNode | null
14
+ * constructor(val?: number, next?: ListNode | null) {
15
+ * this.val = (val===undefined ? 0 : val)
16
+ * this.next = (next===undefined ? null : next)
17
+ * }
18
+ * }
19
+ */
20
+
21
+ function reverseList ( head : ListNode | null ) : ListNode | null {
22
+ if ( ! head ) return null ;
23
+
24
+ const stack : number [ ] = [ ] ;
25
+ let result : ListNode | null = null ;
26
+ let lastNode : ListNode ;
27
+ while ( head ) {
28
+ stack . push ( head . val ) ;
29
+ head = head . next ;
30
+ }
31
+ for ( let i = stack . length - 1 ; i >= 0 ; i -- ) {
32
+ if ( ! result ) {
33
+ result = new ListNode ( stack [ i ] ) ;
34
+ lastNode = result ;
35
+ continue ;
36
+ }
37
+ lastNode . next = new ListNode ( stack [ i ] ) ;
38
+ lastNode = lastNode . next ;
39
+ }
40
+ return result ;
41
+ }
You can’t perform that action at this time.
0 commit comments