File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * TC: O(N)
3+ * SC: O(1)
4+ * N: list length
5+ */
6+
7+ /**
8+ * Definition for singly-linked list.
9+ * function ListNode(val, next) {
10+ * this.val = (val===undefined ? 0 : val)
11+ * this.next = (next===undefined ? null : next)
12+ * }
13+ */
14+ /**
15+ * @param {ListNode } head
16+ * @param {number } n
17+ * @return {ListNode }
18+ */
19+ var removeNthFromEnd = function ( head , n ) {
20+ let listLength = 0 ;
21+ let pointer = head ;
22+
23+ while ( pointer ) {
24+ pointer = pointer . next ;
25+ listLength += 1 ;
26+ }
27+
28+ // if target of removal is the first node in list
29+ if ( listLength === n ) {
30+ return head . next ;
31+ }
32+
33+ let nextCount = listLength - n - 1 ;
34+ pointer = head ;
35+
36+ while ( nextCount ) {
37+ pointer = pointer . next ;
38+ nextCount -= 1 ;
39+ }
40+
41+ pointer . next = pointer . next . next ;
42+
43+ return head ;
44+ } ;
You can’t perform that action at this time.
0 commit comments