题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
这个题目竟然是medium,怕是个easy吧。要求删除链表中倒数第n个节点。
首先想到的就是直接找的待删除节点的前驱结点在执行删除操作就行,这里要注意的是待删除节点可能是头结点的特殊情况,所以用一个虚拟节点来规避,代码如下:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n)
{
if(head==null)
return head;
ListNode virtual=new ListNode(-1);
virtual.next=head;
int length=0;
ListNode p=virtual;
while(p.next!=null)
{
length++;
p=p.next;
}
int k=length-n;
p=virtual;
while(k>0)
{
p=p.next;
k--;
}
ListNode pDeleted=p.next;
p.next=pDeleted.next;
return virtual.next;
}
}
另外一种思路就是快慢指针只要一次遍历就能找到待删除节点的前驱,效率较高,代码如下:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fastPointer = head;
for(int i = 0; i < n; i++)fastPointer = fastPointer.next;
ListNode slowPointer = head;
if(fastPointer == null){
return head.next;
}else{
while(fastPointer.next != null){
fastPointer = fastPointer.next;
slowPointer = slowPointer.next;
}
slowPointer.next = slowPointer.next.next;
}
return head;
}
}