-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add week 7 solutions : removeNthNodeFromEndOfList
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// Time Complexity: O(n) | ||
// Space Complexity: O(1) | ||
|
||
var removeNthFromEnd = function (head, n) { | ||
// calculate the length of the linked list. | ||
let length = 0; | ||
let current = head; | ||
while (current !== null) { | ||
length++; | ||
current = current.next; | ||
} | ||
|
||
// determine the position to remove from the start. | ||
let removeIndex = length - n; | ||
|
||
// if the node to be removed is the head, return the next node. | ||
if (removeIndex === 0) { | ||
return head.next; | ||
} | ||
|
||
// traverse to the node just before the node to be removed. | ||
current = head; | ||
for (let i = 0; i < removeIndex - 1; i++) { | ||
current = current.next; | ||
} | ||
|
||
// remove the nth node from the end. | ||
current.next = current.next.next; | ||
|
||
// return the modified list. | ||
return head; | ||
}; |