要求:用结构体 用链表,实现结构体之间的添加。删除!
简单的就行!比如结构体里有姓名 分数!
今天看了两节课的链表!最终还是无法掌握!
要求:用结构体 用链表,实现结构体之间的添加。删除!
简单的就行!比如结构体里有姓名 分数!
今天看了两节课的链表!最终还是无法掌握!
#include<iostream>
using namespace std;
struct link
{
int data;
link *next;
};
link *hcreat()
{
int i;
link *p,*s;
p=new link;
p->next=NULL;
cout<<"输入数据:";
cin>>i;
while(i)
{
s=new link;
s->data=i;
s->next=p->next;
p->next=s;
cout<<"输入数据:";
cin>>i;
};
return p;
}
link *Locate(link *head,int x)
{
link *p;
p=head->next;
while((p!=NULL)&&(p->data!=x))
{
p=p->next;
}
return p;
}
void insert(link *head,int x,int y)
{
link *p,*s;
s=new link;
s->data=x;
if(head->next==NULL)
{
head->next=s;
s->next=NULL;
}
p=Locate(head,y);
if(p==NULL)
cout<<"error";
else
{
s->next=p->next;
p->next=s;
}
}
void Delete(link *head,int x)
{
link *p,*s;
s=head;
p=head->next;
while((p!=NULL)&&(p->data!=x))
{
s=p;
p=p->next;
}
if(p==NULL)
cout<<"error";
else
{
s->next=p->next;
delete(p);
}
}
void print(link *head)
{
link *p;
p=head->next;
while(p!=NULL)
{
cout<<p->data<<"-";
p=p->next;
}
cout<<endl;
}
int main()
{
link *H;
int k;
int x,y;
do
{
cout<<"\n\n\n\n";
cout<<"\t\t\t链表子系统\n";
cout<<"\t\t***************************\n";
cout<<"\t\t** 1.建 表 **\n";
cout<<"\t\t** 2.插 入 **\n";
cout<<"\t\t** 3.删 除 **\n";
cout<<"\t\t** 4.查 找 **\n";
cout<<"\t\t** 5.显 示 **\n";
cout<<"\t\t** 0.返 回 **\n";
cout<<"\t\t***************************\n";
cout<<"\t\t请输入0-5项:\n";
cin>>k;
switch(k)
{
case 1:
H=hcreat();
break;
case 2:
cout<<"\n请输入插入位置的数值y:";
cin>>y;
cout<<"\n请输入要插入的数据x:";
cin>>x;
insert(H,x,y);
cout<<"插入后链表为:";
print(H);
break;
case 3:
cout<<"\n请输入要删除的元素x:";
cin>>x;
Delete(H,x);
cout<<"删除后链表为:";
print(H);
break;
case 4:
cout<<"\n请输入要查找的数值x:";
cin>>x;
link *p;
p=Locate(H,x);
if(p!=NULL)
{
print(H);
cout<<"值为x所在的位置是"<<p;
}
else
cout<<"链表中无此无素!";
break;
case 5:
cout<<"\n输出线性表:";
print(H);
break;
}
}while(k!=0);
}
这是我学习后写的,可能有些出入。希望能帮助你,