File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ var removeNthFromEnd = function ( head , n ) {
2
+ // Edge case: If the list is empty
3
+ if ( ! head ) return null ;
4
+
5
+ // Create a dummy node that points to the head
6
+ let dummy = new ListNode ( 0 ) ;
7
+ dummy . next = head ;
8
+ let length = 0 ,
9
+ curr = head ;
10
+
11
+ // Calculate the length of the list
12
+ while ( curr ) {
13
+ length ++ ;
14
+ curr = curr . next ;
15
+ }
16
+
17
+ // Find the length-n node from the beginning
18
+ length = length - n ;
19
+ curr = dummy ;
20
+ while ( length > 0 ) {
21
+ length -- ;
22
+ curr = curr . next ;
23
+ }
24
+
25
+ // Skip the desired node
26
+ curr . next = curr . next . next ;
27
+
28
+ // Return the head, which may be a new head if we removed the first node
29
+ return dummy . next ;
30
+ } ;
31
+
32
+ // TC: O(n)
33
+ // SC: O(1)
You can’t perform that action at this time.
0 commit comments