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+ * function ListNode(val, next) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.next = (next===undefined ? null : next)
6+ * }
7+ */
8+ /**
9+ * @param {ListNode } head
10+ * @param {number } n
11+ * @return {ListNode }
12+ */
13+ var removeNthFromEnd = function ( head , n ) {
14+ if ( ! head ) {
15+ return null ;
16+ }
17+
18+ let node = head ;
19+
20+ const list = [ ] ;
21+
22+ while ( node ) {
23+ list . push ( node ) ;
24+ node = node . next ;
25+ }
26+
27+ const targetIndex = list . length - n - 1 ;
28+
29+ if ( targetIndex === - 1 && list . length === 1 ) {
30+ return null ;
31+ }
32+
33+ if ( targetIndex === - 1 ) {
34+ return head . next ;
35+ }
36+
37+ if ( list [ targetIndex ] ) {
38+ list [ targetIndex ] . next = list [ targetIndex ] ?. next ?. next || null ;
39+ }
40+
41+ return head ;
42+ } ;
43+
44+ // ์๊ฐ๋ณต์ก๋ O(n) - ๋
ธ๋๋ฅผ ํ๋ฒ ์ํํ์ฌ ๋ฆฌ์คํธ์ ์ ์ฅ
45+ // ๊ณต๊ฐ๋ณต์ก๋ O(n) - ์ํ ์ดํ์ ์ ๊ฑฐํ ๋
ธ๋์ ๋ฐ๋ก ์ ๋
ธ๋๋ ์ ๊ทผํ๊ธฐ ์ํ์ฌ ๋ชจ๋ ๋
ธ๋๋ฅผ ๋ฐฐ์ด์ ์ ์ฅ
You canโt perform that action at this time.
0 commit comments