Problem:
Given a linked list, remove the n-th node from the end of list and return its head.
Explanation:
将链表中倒数第n个结点移除,返回头结点。
My Thinking:
使用递归,返回到倒数n+1个结点时,将其指针指向后一个结点的后一个结点即可。
My Solution:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fakenode=null;
if(head.next==null)
return null;
else{
fakenode=new ListNode(-1);
fakenode.next=head;
remove(fakenode,n);
}
return fakenode.next;
}
public int remove(ListNode head,int n){
if(head==null)
return 0;
int count=remove(head.next,n)+1;
if(count==n+1){
head.next=head.next.next;
}
return count;
}
}
Optimum Thinking:
使用快慢指针,维持一个fast=slow+n,当fast到达底后,slow就是要被删除的结点的前一个结点。
Optimum Solution:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head;
//将fast指针快进至slow的后n位
for(int i=1; i<=n+1; i++) {
fast = fast.next;
}
//直到fast到底
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
//slow到达被删除结点的前一个结点
slow.next = slow.next.next;
return start.next;
}
}