File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ // Definition for singly-linked list.
2+ public class ListNode {
3+ public var val : Int
4+ public var next : ListNode ?
5+ public init ( ) { self . val = 0 ; self . next = nil ; }
6+ public init ( _ val: Int ) { self . val = val; self . next = nil ; }
7+ public init ( _ val: Int , _ next: ListNode ? ) { self . val = val; self . next = next; }
8+ }
9+
10+ class Solution {
11+ func removeNthFromEnd( _ head: ListNode ? , _ n: Int ) -> ListNode ? {
12+ // ๋ค์์ n๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐพ๊ธฐ ์ํ Two Pointer
13+ var slow = head
14+ var fast = head
15+ var threshold = n
16+
17+ // fast ํฌ์ธํฐ๋ฅผ n๋งํผ ์ด๋์ํด
18+ // ์ ์ฒด ๊ฐฏ์๋ฅผ c๊ฐ๋ผ๊ณ ํ์ ๋, ๋ค์์ n๋ฒ์งธ ๋
ธ๋๋ ์์์ c - n + 1๋ฒ์งธ ๋
ธ๋
19+ while threshold > 0 {
20+ fast = fast? . next
21+ threshold -= 1
22+ }
23+
24+ // padding ๋
ธ๋ ์์ฑ
25+ var prev : ListNode ? = ListNode ( )
26+ // slow ํฌ์ธํฐ์ ์์นํ ๋
ธ๋๋ฅผ ์ ๊ฑฐํ๋ ์ ๋ต - prev ํฌ์ธํฐ๋ฅผ slow ํฌ์ธํฐ์ ์ด์ ๋
ธ๋๋ก ์ด๋์ํด
27+ prev? . next = slow
28+
29+ // ๋ฐํ์ ์ํ result ๋
ธ๋ ํฌ์ธํฐ ์์ฑ
30+ let result = prev
31+
32+ while fast != nil {
33+ prev = prev? . next
34+ slow = slow? . next
35+ fast = fast? . next
36+ }
37+
38+ // fast ๋
ธ๋๋ ๋ฆฌ์คํธ์ ๋ฒ์๋ฅผ ๋ฒ์ด๋ nil์ด ๋์๊ณ ,
39+ // slow ๋
ธ๋๋ ๋ค์์ n๋ฒ์งธ ์๋ฆฌ์ ์์นํด ์์
40+ // ๊ทธ๋ณด๋ค ํ ์นธ ์์ ์๋ prev ๋
ธ๋์ next๋ฅผ, next?.next๋ก ๋ฐ๊ฟ ์ฃผ๋ฉด, slow ๋ถ๋ถ์ ๋
ธ๋ ์ ๊ฑฐ
41+ prev? . next = prev? . next? . next
42+
43+ // ๋ฐํ์ ๋งจ ์์ padding ๋
ธ๋๋ฅผ ์ ๊ฑฐ
44+ return result? . next
45+ }
46+ }
You canโt perform that action at this time.
0 commit comments