题目:
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?
题解:
这道题也是经典题,利用的是fast和slow双指针来解决。
首先先让fast从起始点往后跑n步。
然后再让slow和fast一起跑,直到fast==null时候,slow所指向的node就是需要删除的节点。
注意,一般链表删除节点时候,需要维护一个prev指针,指向需要删除节点的上一个节点。
代码如下:
public class RemoveNthFromEndofList
{
public static void main(String[] args)
{
/**
* 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->6->7, and n = 3.
*
* After removing the second node from the end, the linked list becomes 1->2->3->4->6->7.
* Note:
*
* Given n will always be valid.
*
* Follow up:
*
* Could you do this in one pass?
*/
ListNode ln1 = new ListNode(1);
ListNode ln2 = new ListNode(2);
ListNode ln3 = new ListNode(3);
ListNode ln4 = new ListNode(4);
ListNode ln5 = new ListNode(5);
ListNode ln6 = new ListNode(6);
ListNode ln7 = new ListNode(7);
ln1.next = ln2;
ln2.next = ln3;
ln3.next = ln4;
ln4.next = ln5;
ln5.next = ln6;
ln6.next = ln7;
LeetCodeUtil.printNodeList(removeNthFromEnd(ln1, 3)); // 1->2->3->4->6->7.
LeetCodeUtil.printNodeList(removeNthFromEnd(ln1, 1)); // 1->2->3->4->6.
LeetCodeUtil.printNodeList(removeNthFromEnd(ln1, 5)); // 2->3->4->6.
}
public static ListNode removeNthFromEnd(ListNode head, int n)
{
if (head == null)
{
return head;
}
ListNode fakeHead = new ListNode(0);
fakeHead.next = head;
ListNode fast = fakeHead, slow = fakeHead;
for (int i = 0; i < n; i++)
{
fast = fast.next;
}
while (fast.next != null)
{
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return fakeHead.next;
}
}