File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +45
-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
+ * ์ฃผ์ด์ง ๋จ์ผ ์ฐ๊ฒฐ ๋ฆฌ์คํธ์์ ๋ค์์ N๋ฒ์งธ ๋
ธ๋๋ฅผ ์ ๊ฑฐํ๋ ํจ์
15
+ * @param {ListNode | null } head - ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ์์ ๋
ธ๋
16
+ * @param {number } n - ๋ค์์ n๋ฒ์งธ ๋
ธ๋
17
+ * @returns {ListNode | null } - n๋ฒ์งธ ๋
ธ๋๊ฐ ์ ๊ฑฐ๋ ์๋ก์ด ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ์์ ๋
ธ๋
18
+ *
19
+ * ์๊ฐ ๋ณต์ก๋: O(N)
20
+ * - ์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ฅผ ํ ๋ฒ ์ํํ์ฌ ๊ธธ์ด๋ฅผ ์ฐพ๊ณ , ๋ค์ ํ ๋ฒ ์ํํ์ฌ ๋
ธ๋๋ฅผ ์ญ์ (2N)
21
+ * ๊ณต๊ฐ ๋ณต์ก๋: O(1)
22
+ * - ์ถ๊ฐ์ ์ธ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ์ง ์์ผ๋ฉฐ, ํฌ์ธํฐ๋ง ์ฌ์ฉํ์ฌ ์ฒ๋ฆฌ
23
+ */
24
+ function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
25
+ let headlength = 0 , cur = head ;
26
+
27
+ // ์ ์ฒด ๊ธธ์ด ๊ตฌํ๊ธฐ
28
+ while ( cur ) {
29
+ headlength ++ ;
30
+ cur = cur . next ;
31
+ }
32
+
33
+ // ์ญ์ ํ ๋
ธ๋ ์์น ๊ณ์ฐ (length - n)
34
+ let dummy = new ListNode ( 0 , head ) ;
35
+ cur = dummy ;
36
+ for ( let i = 0 ; i < headlength - n ; i ++ ) {
37
+ cur = cur . next ;
38
+ }
39
+
40
+ // ๋
ธ๋ ์ญ์ (n๋ฒ์งธ ๋
ธ๋ ์ ๊ฑฐ)
41
+ cur . next = cur . next ?. next || null ;
42
+
43
+ return dummy . next ;
44
+ }
45
+
You canโt perform that action at this time.
0 commit comments