尾插法输入以及使用双指针删除点
【样例输入】
10
12 2 31 5 8 2 9 2 9 2
2
【样例输出】
12 31 5 8 9 9
#include<iostream>
#include<cstdio>
using namespace std;
struct node{
int k;
node *next;
};
node *head,*p,*m,*s;
int x;
int main(){
int n;
cin>>n;
head=new node;//申请头结点
m=head;
while(n--){
//尾插法
cin>>x;
p=new node;//申请一个新节点
p->k=x;
p->next=NULL;
m->next=p;//把新节点链接到前面的链表中,实际上m是p的直接前趋
m=p;//尾指针后移一个
}
int t=0;
cin>>t;
p=head->next;
s=head;
while(p->next!=NULL){
if(p->k==t) //判断p是否是要删除的点
{
s->next=p->next;//删除p,即将s指向p的下一个点
free(p);//释放p的空间
p=s->next;//保证p始终在s的前面一点
}
else{
s=p;
p=p->next;
}
}
p=head->next;//从第一个有数据点开始
while(p->next!=NULL){
cout<<p->k<<" ";
p=p->next;
}
}