File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +38
-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+ * n번째 노드 제거하기
14+ * 알고리즘 복잡도
15+ * - 시간 복잡도: O(n)
16+ * - 공간 복잡도: O(n)
17+ * @param head
18+ * @param n
19+ */
20+ function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
21+ let stack : ListNode [ ] = [ ] ;
22+ let node = head ;
23+
24+ while ( node ) {
25+ stack . push ( node ) ;
26+ node = node . next ;
27+ }
28+
29+ // 첫 번째 노드를 제거하는 경우 추가
30+ if ( stack . length - n - 1 < 0 ) {
31+ return head ?. next || null ;
32+ }
33+
34+ const prevNode = stack [ stack . length - n - 1 ] ;
35+ prevNode . next = prevNode . next ?. next || null ;
36+
37+ return head ;
38+ }
You can’t perform that action at this time.
0 commit comments