Given a linked list, remove the n-th node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
public ListNode removeNthFromEnd(ListNode head, int n) { // ListNode defined in AddTwoNumbers
ListNode end = head, targetAhead = null;
int i = 0;
// Let targetAhead point to the node ahead the one to be removed.
// If such node does not exist, always remove the first node
while (end.next != null) {
end = end.next;
i++;
if (i == n)
targetAhead = head;
else if (i > n)
// Maintain the distance of n between end and targetAhead
targetAhead = targetAhead.next;
}
// Consider the cases of removing the first node and any of the remaining nodes
if (targetAhead == null)
return head.next;
else {
targetAhead.next = targetAhead.next.next;
return head;
}
}
Read full article from LeetCode - Remove Nth Node From End of List | Darren's Blog
No comments:
Post a Comment