File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+
You canโt perform that action at this time.
0 commit comments