#include <iostream>
using namespace std;
class List //定义单链表的结构
{
public:
int num;
class List *next;
void create();
void print();
void find();
void inser();
void dele();
void choose();
};
typedef class List Node; //将class List再命名为Node
typedef Node *Link; //声明单链表的指针
Link top,p,s;
void List::choose()
{
List List1;
int r;
bool toD = true;
while(toD)
{
cout<<"1, input data create a new table"<<endl;
cout<<"2, print the table"<<endl;
cout<<"3, find digital in the table"<<endl;
cout<<"4, insert digital in the table"<<endl;
cout<<"5, delete digital in the table"<<endl;
cout<<"press the other key, select exit"<<endl;
cin>>r;
switch (r)
{
case 1:
List1.create(); //创建链表
break;
case 2:
List1.print(); //显示表中的数据
break;
case 3:
List1.find(); //查找链表中的数据
break;
case 4:
List1.inser(); //在链表中插入数据
break;
case 5:
List1.dele(); //在链表中删除数据
break;
default:
toD = false;
break;
}
}
}
void List::create() //创建链表
{
int c;
bool toC = true;
top = new Node;
(*top).next = NULL;
p = top;
while(toC)
{
cout<<"choose 1,input data";
cout<<endl;
cout<<"press the other key,the table is fulfil";
cout<<endl;
cin>>c;
switch (c)
{
case 1:
cout<<"input the data you want in the table";
cout<<endl;
s = new Node;
cin>>(*s).num;
(*p).next = s;
(*s).next = NULL;
p = (*p).next;
break;
default:
toC = false;
break;
}
}
print();
}
void List::print() //显示
{
p = (*top).next;
while(p)
{
cout<<(*p).next<<"\t"<<"\t"<<(*p).num<<endl;
p = (*p).next;
}
}
void List::find() // 查找
{
int j = 1;
int i;
p = (*top).next;
cout<<"please enter you want find position with "<<endl;
cin>>i;
while(p && j<i)
{
p = (*p).next;
j++;
}
if(!p)
{
cout<<"seek error!";
cout<<endl;
}
else
{
cout<<p<<"\t"<<"\t"<<(*p).num;
cout<<endl;
}
}
void List::inser() //插入
{
int j = 0;
int i;
p = (*top).next;
cout<<"please input you want insert number"<<endl;
cin>>num;
cout<<"please input you want insert position"<<endl;
cin>>i;
while(p && j<i-1)
{
p = (*p).next;
j++;
}
if(!p)
{
cout<<"insert error!";
cout<<endl;
}
else
{
Link s;
s = new Node;
(*s).num = num;
(*s).next = (*p).next;
(*p).next = s;
}
print();
}
void List::dele() //删除
{
int j = 0;
int i;
p = top;
cout<<"please input you want delete position"<<endl;
cin>>i;
while(p && j<i-1)
{
p = (*p).next;
j++;
}
if(!p)
{
cout<<"delete error!";
cout<<endl;
}
else
{
s = new Node;
s = (*p).next;
(*p).next = (*s).next;
}
print();
}
int main()
{
List List1; //实例化一个类
List1.choose();
return 0;
}
转载于:https://my.oschina.net/readerlhx/blog/286374