您的位置:首页 > 其它

从单向链表中删除指定值的节点(格式控制真坑,末尾要打印空格,样例输出有错误)

2017-06-12 18:51 323 查看
#include<iostream>
using namespace std;
struct ListNode
{
int  val;
ListNode* next;
};
int main()
{
int n,head_value;
while(cin>>n>>head_value)
{
ListNode *p,*q,*head=new ListNode;
head->val=head_value;
head->next=NULL;
q=head;
for(int i=0; i<n-1; i++)
{
int x,y;
cin>>x>>y;
p=new ListNode;
p->val=x;
p->next=NULL;
while(q)
{
if(q->val==y)
{
p->next=q->next;
q->next=p;
break;
}
else
q=q->next;
}
q=head;
}
int denum;
cin>>denum;
q=head;
while(q)
{
if(q->val==denum)
{
if(q==head)
{
head=q->next;
delete q;
}
else
{
p->next=q->next;
delete q;
}
break;
}
else
{
p=q;
q=q->next;
}
}
q=head;
while(q)
{
cout<<q->val<<' ';
q=q->next;
}
cout<<endl;
}
return 0;
}

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
list<int>L;
list<int>::iterator it;
int x,y;
cin>>x;
L.push_back(x);
for(int i=1; i<n; i++)
{
cin>>x>>y;
it=find(L.begin(),L.end(),y);
if(it!=L.end())
{
advance(it,1);
L.insert(it,x);
}
}
cin>>x;
it=find(L.begin(),L.end(),x);
if(it!=L.end())
L.erase(it);
for(it=L.begin(); it!=L.end(); it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法