Given a linked list, remove the n th node from the end of list and return its head.
For 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.
思路:
需要删除的倒数第n个结点,它的前驱结点与链表的尾节点相差n,开始slow=fast=head,首先fast指针前移n个结点,若fast指针为空,则要删除的结点为第一个结点,直接返回head.next;若fast指针不为空,则slow和faster同时向前移动,slow最终指向的结点就是要删除结点的前驱结点。
public ListNode RemoveNthFromEnd(ListNode head,int n) {
if(head==null||n<=0){
return head;
}
ListNode helper=new ListNode(0);
helper.next=head;
ListNode slow=head;
ListNode fast=head;
for(int i=0;i<n;i++){
fast=fast.next;
}
if(fast==null){
return head.next; //表示要删除的是第一个结点
}
while(fast.next!=null){ //找到最后一个结点的条件都是这样的
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;
return helper.next;
}
自己开始想的思路错误,一开始编写的代码
public ListNode reverseList(ListNode l){
ListNode pre=new ListNode(0);
ListNode cur=l;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre.next;
pre.next=cur; //头插法
cur=next;
}
return pre.next;
}
public ListNode RemoveNthFromEnd(ListNode head,int n) {
ListNode after=reverseList(head);
ListNode front=after;
ListNode p;
n=n-2;
while(n>0){
n--;
front=front.next;
}
p= front.next; //p指向需要删除的数,front指向要删除数的前驱结点
front.next=p.next;
return reverseList(after);
}