您的位置:首页 > Web前端 > Node.js

19. Remove Nth Node From End of List

2016-04-26 09:35 585 查看
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *temp=head;
int count=0;
while(temp)
{
count++;
temp=temp->next;
}
int del=count-n+1;
ListNode *prenode=new ListNode(-1);
ListNode *pre=prenode;
pre->next=head;
temp=head;
count=1;
while(temp) {
if (count == del) {
pre->next = pre->next->next;
break;
}
pre=temp;
temp=temp->next;
count++;
}
return prenode->next;
}
};


这是第二种解决方法 整个过程只需要遍历一遍 当后指针指向n+2个节点的时候 前指针指向第一个数 当后指针为null的时候 前指针指向倒数第n个节点的前驱节点。

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head)
return head;

ListNode *prehead=new ListNode(-1);
if(!head->next&&n==1)
return NULL;
prehead->next=head;
ListNode *first=NULL;
ListNode *tail=prehead;
int count=1;
while(tail)
{
if(count==n+2)
{
first=prehead;
}
tail=tail->next;
count++;
if(first)
first=first->next;
}
if(count==n+2)
{
first=prehead;
}
first->next=first->next->next;
return prehead->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: