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.
Follow up:
-- Could you do this in one pass?
Solution
-- 快慢指针
-- 快指针先走n
步,然后快慢指针同时再一起走。当快指针走到尾部时,慢指针后面那个节点,就是要删除的第n
个节点。
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//Two pointer, firstly move fast pointer n steps, and then move slow and fast together,
// when fast reaches the end node, the nth node is the next node of the slow pointer.
if (head == null || n < 1)
{
return head;
}
ListNode dummy = new ListNode (0);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
for (int i = 0; i < n; i++)
{
fast = fast.next;
}
while (fast.next != null)
{
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}