#include "stdafx.h"
#include <iostream>
using namespace std;
struct Data //结构体定义
{
int data;
Data *next;
};
int n;
int main ( ) //主函数
{Data * creat(void ) ; //声明创建函数
Data * del(Data * ,int );//声明删除函数
Data *insert (Data * head,Data * da);//声明插入函数
void print (Data *head);//声明输出函数
int look(Data *head, int a); // 声明查找函数
Data * head,*da;
int b,m;
da=new Data ;
head=creat (); //创建函数
print (head); //输出函数
cout <<"please input the data you insert: "<<endl;
cin >>da->data;
head=insert (head,da);//插入函数
print (head); //输出函数
cout <<"please input the data you delete : "<<endl;
cin >>b;
head=del(head,b); //删除函数
print (head); //输出函数
cout <<"please input the data you look : "<<endl;
cin >>m;
look(head,m); //查找函数
return 0;
}
Data * creat(void ) //定义创建函数
{Data *p1,*p2,*head;
n=0;
p1=p2=new Data;
cout <<"Please input data: "<<endl;
cin>>p1->data;
head=NULL;
while (p1->data!=0)
{n++;
if (n==1)
head=p1;
else p2->next=p1;
p2=p1;
p1=new Data;
cout <<"Please input data:"<<endl;
cin>>p1->data;}
p2->next=NULL;
return (head);
}
void print (Data *head)//定义输出函数
{Data *p1;
p1=head;
if (head==NULL)
cout <<"list null"<<endl;
else
{cout <<endl<<"The datas are : "<<endl;
do{cout <<p1->data<<endl;
p1=p1->next;}while (p1!=NULL);
}
}
int look(Data *head, int a) //查找函数
{Data *p1;
int m=0;
p1=head;
if (head==NULL)
{cout <<endl<<"List null"<<endl;return 0;}
while (p1->next!=0)
{if (p1->data==a)
m=m+1;
p1=p1->next;}
cout <<endl<<"There is "<<m<<" data"<< a<<"!!"<<endl;
return 0;
}
Data *insert (Data * head,Data * da)//定义插入函数
{Data *p1,*p2;
p1=head;
if (head==NULL)
{head=da;
da->next=NULL;
}
else
{while (da->data>p1->data)
{p2=p1;
p1=p1->next;
}
if (da->data<=p1->data )
{if (head==p1)
head=da;
else p2->next=da;
da->next =p1;
}
else {p1->next=da;da->next =NULL;}
n=n+1;}
return head;
}
Data *del (Data * head,int da) //定义查找并删除函数
{Data *p1,*p2;
p1=head;
if (head ==NULL)
cout <<"List null"<<endl;
while (da!=p1->data&&p1->next!=NULL)
{p2=p1;
p1=p1->next;
}
if(da==p1->data)
{if (p1==head)
head=p1->next;
else p2->next=p1->next;
cout <<"delete "<<da<<"!"<<endl;
}
else cout <<"cannot find"<<da<<"!"<<endl;
return head;
}