File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * [Problem]: [19] Remove Nth Node From End of List
3+ * (https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/)
4+ */
5+
6+ class ListNode {
7+ val : number ;
8+ next : ListNode | null ;
9+ constructor ( val ?: number , next ?: ListNode | null ) {
10+ this . val = val === undefined ? 0 : val ;
11+ this . next = next === undefined ? null : next ;
12+ }
13+ }
14+
15+ function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
16+ // 시간복잡도 O(N)
17+ // 공간복잡도 O(1)
18+ function lengthFunc ( head : ListNode | null , n : number ) : ListNode | null {
19+ let length = 0 ;
20+ let current = head ;
21+ while ( current ) {
22+ length ++ ;
23+ current = current . next ;
24+ }
25+
26+ let dummy = new ListNode ( 0 , head ) ;
27+ current = dummy ;
28+
29+ for ( let i = 0 ; i < length - n ; i ++ ) {
30+ current = current ?. next ! ;
31+ }
32+
33+ current . next = current . next ! . next || null ;
34+
35+ return dummy . next ;
36+ }
37+
38+ // 시간복잡도 O(N)
39+ // 공간복잡도 O(1)
40+ function twoPointerFunc ( head : ListNode | null , n : number ) : ListNode | null {
41+ let first = head ;
42+
43+ for ( let i = 0 ; i < n ; i ++ ) {
44+ first = first ?. next ! ;
45+ }
46+
47+ let dummy = new ListNode ( 0 , head ) ;
48+ let second = dummy ;
49+
50+ while ( first ) {
51+ first = first . next ;
52+ second = second . next ! ;
53+ }
54+
55+ second . next = second . next ?. next || null ;
56+ return dummy . next ;
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments