Skip to content

Commit 6ecb44d

Browse files
committed
feat: reverse-linked-list solution
1 parent 89edeec commit 6ecb44d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

reverse-linked-list/YeomChaeeun.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 연결 리스트를 뒤집는 알고리즘
3+
* 알고리즘 복잡도
4+
* - 시간 복잡도: O(n)
5+
* - 공간 복잡도: O(n)
6+
*/
7+
/**
8+
* Definition for singly-linked list.
9+
* class ListNode {
10+
* val: number
11+
* next: ListNode | null
12+
* constructor(val?: number, next?: ListNode | null) {
13+
* this.val = (val===undefined ? 0 : val)
14+
* this.next = (next===undefined ? null : next)
15+
* }
16+
* }
17+
*/
18+
function reverseList(head: ListNode | null): ListNode | null {
19+
// console.log(head)
20+
if (head === null || head.next === null) {
21+
return head
22+
}
23+
24+
// 마지막 노드에 도달할 때까지 계속 재귀 호출
25+
const newHead = reverseList(head.next)
26+
27+
// 백트래킹 과정
28+
head.next.next = head
29+
head.next = null
30+
31+
return newHead
32+
}

0 commit comments

Comments
 (0)