File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Source: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3
+ * Solution: ๋ ๊ฐ์ ํฌ์ธํฐ๋ฅผ ์ด์ฉํด n๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐพ์ ์ญ์
4
+ *
5
+ * ์๊ฐ๋ณต์ก๋: O(N) - ๋ ๊ฐ์ ํฌ์ธํฐ๊ฐ ํ๋ฒ์ฉ ์ํ
6
+ * ๊ณต๊ฐ๋ณต์ก๋: O(1) - ์์๋งํผ์ ๊ณต๊ฐ ์ฌ์ฉ
7
+ */
8
+
9
+ function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
10
+ if ( ! head ) return null ;
11
+
12
+ const dummy = new ListNode ( 0 , head ) ;
13
+ let slow : ListNode | null = dummy ;
14
+ let fast : ListNode | null = dummy ;
15
+
16
+ for ( let i = 0 ; i <= n ; i ++ ) {
17
+ if ( ! fast ) return head ;
18
+ fast = fast . next ;
19
+ }
20
+
21
+ while ( fast ) {
22
+ slow = slow ! . next ;
23
+ fast = fast . next ;
24
+ }
25
+
26
+ if ( slow && slow . next ) {
27
+ slow . next = slow . next . next ;
28
+ }
29
+
30
+ return dummy . next ;
31
+ }
You canโt perform that action at this time.
0 commit comments