/*链表的正向建立—头插法 & 链表的逆向建立—尾插法 算法2.11*/
#include<iostream>
#define OK 1
#define ERROR 0
int a,b;
using namespace std;
struct node
{
int date;
node *next;
};
class List
{
node *head;
public:
List() {head=NULL;}
int choice(int a);
void inser_infront(int b); //头插
void inser_inend(int b); //尾插
void output();
};
int List::choice(int a)
{
if (a==0)
inser_infront(b);
else if(a==1)
inser_inend(b);
else if(a==2)
{
if(head==NULL)
cout<<"抱歉,暂时链表里面无可打印数据!!!"<<endl;
else
output();
}
else
return ERROR;
}
void List:: inser_infront(int b)
{
node *p,*s; //p指向链表节点的指针 s新增的节点
cout<<"请输入要插入的数据:";
cin>>b;
p=head;
s=new node();
s->date=b;
s->next=NULL;
if(head==NULL)
head=s;
else
{
s->next=p;
head=s;
}
}
void List:: inser_inend(int b)
{
cout<<"请输入要插入的数据:";
node *p,*s;
cin>>b;
s=new node();
s->date=b;
s->next=NULL;
if (head==NULL)
head=s;
else
{
p=head;
while (p->next!=NULL)
{p=p->next;}
p->next=s;
}
}
void List::output()
{
node *p;
p=head;
cout<<"现在的链表为:";
while (p->next!=NULL)
{
cout<<p->date<<",";
p=p->next;
}
cout<<p->date<<endl;;
}
int main()
{
List L;
while (1)
{
cout<<"0:在链表前端插入数据"<<endl<<"1:在链表尾端插入数据"<<endl<<"2:打印链表"<<endl;
cout<<"你的选择是:";
cin>>a;
L.choice(a);
}
return 0;
}