Skip to content

Commit 3df0940

Browse files
committed
feat: Upload reserve-linked-list(typescript)
1 parent d02ead8 commit 3df0940

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

reverse-linked-list/mike2ox.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)