-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 56 ms (58.72%) | Memory: 50.9 MB (15.73%) - LeetSync
- Loading branch information
1 parent
c78fc6a
commit f71a43b
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
19-remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js
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,36 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* function ListNode(val, next) { | ||
* this.val = (val===undefined ? 0 : val) | ||
* this.next = (next===undefined ? null : next) | ||
* } | ||
*/ | ||
/** | ||
* @param {ListNode} head | ||
* @param {number} n | ||
* @return {ListNode} | ||
*/ | ||
var removeNthFromEnd = function(head, n) { | ||
// Create a dummy node to handle cases where the head is removed | ||
const dum = new ListNode(0); | ||
dum.next = head; | ||
|
||
// Initialize two pointers: first and second | ||
let first = dum; | ||
let scnd = dum; | ||
|
||
// Move the first pointer n nodes ahead of the second pointer | ||
for ( let i = 0; i < n + 1; i++){ | ||
first = first.next; | ||
} | ||
while(first !== null){ | ||
first = first.next; | ||
scnd = scnd.next; | ||
} | ||
|
||
// Remove the nth node from the end by adjusting pointers | ||
scnd.next = scnd.next.next; | ||
|
||
// Return the head of the modified linked list | ||
return dum.next; | ||
}; |