c++关于结构体动态链表初始化添加删除操作代码

来源:互联网 发布:分享wifi的软件 编辑:程序博客网 时间:2024/05/22 16:04
#include<iostream> 
using namespace std;  
struct Student{
int id;
Student *next;
}*p,*head;




void greate(){
head=new Student;
head=NULL;
p=head;
cout<<"please enter student number:";
int n;
cin>>n;
for(int i=0;i<n;i++){
p=new Student;
p->id=i;
p->next=head; //此方法开始是 p->next=0(head->next=NULL),p->next=1 
head=p; //head移动到p(0)位置,head移动到p(1)位置,尾插法,最后的head移动到了n-1的位置,p和head都成了第一个出来的数,NULL 被推到了后面 
}
}


void prin(){
p=head;
while(p!=NULL){
cout<<p->id<<endl;
p=p->next;
}
 
}


void insert(){
int n;
Student *sert,*nex;
sert=new Student;
sert->id=100;
cout<<"place:";
cin>>n;

p=head;
while(p->id!=n)
p=p->next; //插入到n后面 

nex=p->next;
p->next=sert; //顺序可不能乱编 
sert->next=nex;
}


void deleter(){
int number;
Student *out=new Student;
cout<<"number of:";//删除掉5 
cin>>number;

p=head;
while(p->id!=number){
out=p;
p=p->next;
}
out->next=p->next;
 

}


int main(){




greate();
prin();
insert();
prin();
deleter();
prin();
阅读全文
0 0
原创粉丝点击