Given a linked list, remove the n-th node from the end of list and return its head.
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.
Note:
Given n will always be valid.
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(0);
ListNode slow = start;
ListNode fast = start;
start.next = head;
for (int i = 1; i <= n; i++) {
fast = fast.next;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return start.next;
}
fast和slow之间的间隔为n-1,当fast移动到最后一个结点时,slow在需要删除的结点之前,修改slow的next指针即可删掉指定结点。