Skip to content

Commit e69fc8d

Browse files
committed
add: solve #223 Reverse Linked List with ts
1 parent a34edf6 commit e69fc8d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
/**
14+
* linked list ๋ฅผ ๋’ค์ง‘๋Š” ํ•จ์ˆ˜.
15+
*
16+
* @param {ListNode | null} head - linked list ์˜ ์‹œ์ž‘ ๋…ธ๋“œ
17+
* @returns {ListNode | null} ๋’ค์ง‘ํžŒ ๋‹จ์ผ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘ ๋…ธ๋“œ
18+
*
19+
* - ์‹œ๊ฐ„ ๋ณต์žก๋„(Time Complexity): O(n)
20+
* - llinked list ๊ธธ์ด ๋งŒํผ ์ˆœํšŒ
21+
*
22+
* - ๊ณต๊ฐ„ ๋ณต์žก๋„(Space Complexity): O(1)
23+
*/
24+
function reverseList(head: ListNode | null): ListNode | null {
25+
let prev: ListNode | null = null;
26+
let curr: ListNode | null = head;
27+
28+
while (curr !== null) {
29+
const next: ListNode | null = curr.next; // ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ์ž ์‹œ ์ €์žฅ
30+
curr.next = prev; // ํ˜„์žฌ ๋…ธ๋“œ์˜ next๋ฅผ ์ด์ „ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ๋ณ€๊ฒฝ
31+
prev = curr; // prev๋ฅผ ํ˜„์žฌ ๋…ธ๋“œ๋กœ ์—…๋ฐ์ดํŠธ
32+
curr = next; // curr๋ฅผ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™
33+
}
34+
35+
return prev; // prev๊ฐ€ ๋’ค์ง‘ํžŒ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์‹œ์ž‘ ๋…ธ๋“œ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.
36+
};
37+

0 commit comments

Comments
ย (0)