File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +34
-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+ function removeNthFromEnd ( head : ListNode | null , n : number ) : ListNode | null {
14+ if ( ! head ) return null ;
15+
16+ let current = head ;
17+ let nodeLen = 0 ;
18+ while ( current . next ) {
19+ current = current . next ;
20+ nodeLen ++ ;
21+ }
22+
23+ if ( nodeLen - n < 0 ) return head . next ;
24+
25+ current = head ;
26+ let count = 0 ;
27+ while ( count < nodeLen - n ) {
28+ current = current . next ;
29+ count ++ ;
30+ }
31+ current . next = current . next . next ;
32+
33+ return head ;
34+ }
You can’t perform that action at this time.
0 commit comments