Skip to content

Commit 2839bd9

Browse files
committed
#223 reverse linked list
1 parent 2e0adfb commit 2839bd9

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Definition for singly-linked list.
2+
class ListNode {
3+
val: number
4+
next: ListNode | null
5+
constructor(val?: number, next?: ListNode | null) {
6+
this.val = (val===undefined ? 0 : val)
7+
this.next = (next===undefined ? null : next)
8+
}
9+
}
10+
11+
function reverseList(head: ListNode | null): ListNode | null {
12+
let prev: ListNode | null = null;
13+
let current = head;
14+
let next = null;
15+
16+
while (current !== null) {
17+
const next = current.next; // 1. ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๊ธฐ์–ตํ•ด๋‘๊ณ 
18+
current.next = prev; // 2. ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ ์ด์ „ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก
19+
prev = current; // 3. ์ด์ „ ๋…ธ๋“œ๋ฅผ ์ง€๊ธˆ ๋…ธ๋“œ๋กœ ์—…๋ฐ์ดํŠธ
20+
current = next; // 4. ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™
21+
}
22+
23+
24+
return prev;
25+
};

0 commit comments

Comments
ย (0)