#include<iostream>
using namespace std;
struct node{ //定义节点//
int data;
node *next;
};
class sllist{ //单链表类的定义//
private:
node *head;
public:
sllist();
node *creat_list(); //创建链表的函数//
void print_list(); //输出链表//
void find(); //存取//
void search(); //查找//
node * insert(); //插入//
node * del(); //删除//
};//构造函数//
sllist::sllist(){
cout<<"警告:如果你输入的数据超过链表的范围程序会终止!"<<endl;
head=new node;
}//创建链表//
node * sllist::creat_list(){
int n=1;
node *p1,*p2;
p1=new node;
cout<<"请输入第1个数据:"<<endl;
cin>>p1->data;
head->next=p1;
while(p1->data!=0){
n++;
p2=p1;
p1=new node;
p2->next=p1;
cout<<"请输入第"<<n<<"个数据:"<<endl;
cin>>p1->data;
};
p2->next=NULL;
return 0;
}//打印链表//
void sllist::print_list(){
node *p;
int n=0;
p=head->next;
cout<<"你输入的数据如下:"<<endl;
if(head!=NULL)
do
{
n++;
cout<<"第"<<n<<"个数据为:"<<p->data<<endl;
p=p->next;
}while(p!=NULL);
}//存取//
void sllist::find(){
int k;
int i;
node *p;
cout<<"你要查找第?个数据:"<<endl;
cin>>k;
p=head->next;
if(head!=NULL)
for(i=0;i<k-1;i++)
p=p->next;
cout<<"你要查找的数据为:"<<endl;
cout<<p->data<<endl;
}//查找//
void sllist::search(){
int item;
node *p;
int n=0;
p=head->next;
cout<<"请输入你要查找的数据:"<<endl;
cin>>item;
if(head!=NULL)
do{
n++;
if(p->data==item)
cout<<"你要找的数据存在且是第"<<n<<"个"<<endl;
p=p->next;
}while(p!=NULL);
}//插入//
node * sllist::insert(){
int k,i;
int item;
int choice;
node *p=head->next,*temp;
cout<<"请输入你要插入的数据的值:"<<endl;
cin>>item;
cout<<"要在链表头增加请输入1;否则请输入2。"<<endl;
cin>>choice;
switch(choice)
{
case 1:temp=new node;
temp->data=item;
head->next=temp;
temp->next=p;
break;
case 2:cout<<"请问你要在第几个节点后增加数据?:"<<endl;
cin>>k;
for(i=0;i<k-1;i++)
p=p->next;
temp=new node;
temp->data=item;
temp->next=p->next;
p->next=temp;
break;
default:break;
};
return head;
}//删除//
node * sllist::del(){
node *p=head;
node *temp;
int k,i;
cout<<"请问你要删除第几个节点?"<<endl;
cin>>k;
for(i=0;i<k-1;i++)
p=p->next;
temp=p;
temp=temp->next;
p->next=temp->next;
return head;
}
int main(){
sllist x;
x.creat_list();
x.print_list();
x.find();
x.search();
x.insert();
x.print_list();
x.del();
x.print_list();
return 0;
}