19. Remove Nth Node From End of List
https://leetcode.com/problems/remove-nth-node-from-end-of-list
Python
(First Run)
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(val=-1, next=head)
cur_1 = dummy
cur_2 = dummy
for i in range(0, n+1):
cur_1 = cur_1.next
while cur_1 is not None:
cur_1 = cur_1.next
cur_2 = cur_2.next
cur_2.next = cur_2.next.next
return dummy.next
(Second Run)
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
cur = head
length = 0
while cur:
cur = cur.next
length += 1
dummy = ListNode(val=-1, next=head)
cur = dummy
for i in range(length-n):
cur = cur.next
cur.next = cur.next.next if cur.next else cur.next
return dummy.next
Javascript
var removeNthFromEnd = function(head, n) {
let prevNode = null;
let currNode = head;
while (currNode !== null) {
const nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
currNode = new ListNode(0, prevNode);
prevNode = null;
let count = 0
while (currNode !== null) {
const nextNode = n - 1 === count ? currNode.next.next : currNode.next;
currNode.next = prevNode;
prevNode = count === 0 ? prevNode : currNode;
currNode = nextNode;
count++;
}
return prevNode;
};