题目描述
给定一个链表,删除链表的倒数第 n 个节点。例如,给定一个链表: 1 -> 2 -> 3 -> 4 -> 5, 和 n = 2。当删除了倒数第二个节点后,链表变为 1 -> 2 -> 3 -> 5。
你可以假设,给定的 n 是有效的。额外要求就是,要在一趟扫描中实现,即时间复杂度是 O(n)。
方法
快慢指针。
public static Node deleteLastn(Node head, int n) {
Node fast = head;
Node low = head;
if(length(head)==n) {
return head.next;
}
while(n>0) {
fast=fast.next;
n--;
}
while (fast.next != null) {
fast = fast.next;
low = low.next;
}
low.next = low.next.next;
return head;
}
这里要注意一个特殊情况,即n=链表长度时。