Title:
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Test Instructions:
Given a linked list, remove the nodes of the nth node of the tail nodes and return the head node after the node is removed.
For example:
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
The given n is valid.
Try to get the results at once.
Algorithm Analysis:
Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When the fast reaches the end, the slow pointer points at the previous element of the target element.
Use a fast and slow double pointer. The fast pointer is n steps before the slow pointer. When the fast pointer reaches the end of the list, the slow pointer points exactly to the first element of the target element.
AC Code:
public class Solution {public ListNode removenthfromend (listnode head, int n) { if (head = = null) return null; ListNode fast = head; ListNode slow = head; for (int i=0; i<n; i++) { fast = Fast.next; } If remove the first node if (fast = = null) { head = Head.next; return head; } while (fast.next! = null) { fast = Fast.next; slow = Slow.next; } Slow.next = Slow.next.next; return head; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Remove Nth Node from End of List