Created
January 18, 2020 11:53
-
-
Save dashsaurabh/342b53385b72858575bd7f9575da10f2 to your computer and use it in GitHub Desktop.
Remove nth or kth node from a singly linked list in single pass
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
/** | |
* Definition for singly-linked list. | |
* function ListNode(val) { | |
* this.val = val; | |
* this.next = null; | |
* } | |
*/ | |
/** | |
* @param {ListNode} head | |
* @param {number} n | |
* @return {ListNode} | |
*/ | |
var removeNthFromEnd = function(head, n) { | |
let dummyNode = new ListNode(0); | |
dummyNode.next = head; | |
let first = dummyNode; | |
let second = dummyNode; | |
let counter = 0; | |
while(counter < n + 1){ | |
first = first.next; | |
counter++; | |
} | |
while(first !== null) { | |
first = first.next; | |
second = second.next; | |
} | |
second.next = second.next.next; | |
return dummyNode.next; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment