纯粹看了书之后自己想着打的,所以可能有藏着一些BUG没有发现,看看以后能不能找到。
上代码:
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct link{
int data;
struct link *next;
} linklist; //基本链表结构
void Inputdata(linklist *head) //给链表输入数据,同时生成新的节点
{
int a,count=0;
cout<<"Input the digit data of the linklist,0 is over."<<endl<<endl;
linklist *p=head;
while(cin>>a&&a)
{
p->next=(linklist*)malloc(sizeof(linklist));
p=p->next;
p->data=a;
p->next=NULL;
count++;
}
cout<<"The number of data is "<<count<<endl<<endl;
}
void Search(linklist* head) //查找链表中的某个值
{
cout<<"Input the data you want to search,0 is over."<<endl<<endl;
int a;
while(cin>>a&&a)
{
bool flag=true;
int count=1;
linklist *p=head->next;
while(1)
{
if(p->data==a){
cout<<"The number of data is "<<count<<endl<<endl;
flag=false;
break;
}
else
p=p->next;
count++;
if(!p)
break;
}
if(flag)
cout<<"Can't find the number."<<endl<<endl;
}
cout<<endl;
}
void Deletedata(linklist *head) //删除链表中的内容
{
cout<<"Input the number you want to delete , 0 is over "<<endl<<endl;
int a;
while(cin>>a&&a)
{
linklist *p=head,*q=head;
int count=0;
bool flag=true;
while(p)
{
if(p->next->data==a){
q=p->next;
p->next=q->next;
free(q); //记得free掉不用的节点
cout<<"Delete has been done."<<endl<<endl;
flag=false;
break;
}else
p=p->next;
}
if(flag)
cout<<"Can't find the number"<<endl<<endl;
cout<<endl;
}
}
void Insertdata(linklist *head) //给链表插入内容
{
cout<<"Input the number you want to insert and where you want to insert ,number and place of 0 is over."<<endl;
int a,b;
while(cin>>a>>b&&(a||b))
{
linklist *q=(linklist *)malloc(sizeof(linklist));
linklist *p=head->next;
int j=0;
bool flag=true;
while(p)
{
if(j==b){
q->data=a;
q->next=p->next;
p->next=q;
flag=false;
cout<<"Insert has been done."<<" "<<b<<" "<<j<<endl;
break;
}
j++;
}
if(flag)
cout<<"Can't insert the number,the number of place is wrong."<<endl;
}
cout<<endl;
}
int main()
{
linklist *head=(linklist*)malloc(sizeof(linklist));//创建头指针
Inputdata(head);
Search(head);
Deletedata(head);
Insertdata(head);
return 0;
}