乘风破浪:LeetCode真题_019_Remove Nth Node From End of List
一、前言
这次总算到了链表的操作了,之后肯定会有排序算法,二叉树,排序树,图等等的操作,现在我们先从链表开始。
二、Remove Nth Node From End of List
2.1 问题

2.2 分析与解决
其实这个问题真的不难,只要知道了链表的长度,然后做一个减法就能找到需要移除的节点了,但是题目上说可以在一次遍历之内就完成运算吗?这就有点难度了,我们可能一时想不开,作为单向链表,又怎么能完成这样巧妙的任务呢?!于是有人告诉我们,在原有的架构不能解决的时候,我们就需要用空间换时间了,那么到底要怎么做呢?这个空间就是再生成一个指针,利用对称性来完成。这是非常巧妙的。
我们先看两次遍历的算法:
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
int length = 0;
ListNode first = head;
while (first != null) {
length++;
first = first.next;
}
length -= n;
first = dummy;
while (length > 0) {
length--;
first = first.next;
}
first.next = first.next.next;
return dummy.next;
}
然后是一次遍历的:
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}

从示意图上我们可以清楚地看出通过两个指针一次遍历就能锁定目标。
三、总结
有的时候在某种情况下不可能的事情,如果加入了一些指针和思想就能产生很非凡的作用了。