File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(1)
3
+
4
+ var removeNthFromEnd = function ( head , n ) {
5
+ // calculate the length of the linked list.
6
+ let length = 0 ;
7
+ let current = head ;
8
+ while ( current !== null ) {
9
+ length ++ ;
10
+ current = current . next ;
11
+ }
12
+
13
+ // determine the position to remove from the start.
14
+ let removeIndex = length - n ;
15
+
16
+ // if the node to be removed is the head, return the next node.
17
+ if ( removeIndex === 0 ) {
18
+ return head . next ;
19
+ }
20
+
21
+ // traverse to the node just before the node to be removed.
22
+ current = head ;
23
+ for ( let i = 0 ; i < removeIndex - 1 ; i ++ ) {
24
+ current = current . next ;
25
+ }
26
+
27
+ // remove the nth node from the end.
28
+ current . next = current . next . next ;
29
+
30
+ // return the modified list.
31
+ return head ;
32
+ } ;
You can’t perform that action at this time.
0 commit comments