19 - Remove Nth Node From End of List
Written on October 21, 2015
Tweet
Given a linked list, remove the nth node from the end of list and return its head.
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curr = dummy, slow = dummy;
for (int i = 0; i < n; i++) {
curr = curr.next;
}
while (curr.next != null) {
slow = slow.next;
curr = curr.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head:
return
dummy = ListNode(0)
dummy.next = head
slow = fast = dummy
for i in range(n + 1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next