您的位置:首页 > 理论基础 > 数据结构算法

数据结构 P30 算法实现 链表的头插法 尾插法

2017-09-30 16:05 399 查看
/*链表的正向建立—头插法 & 链表的逆向建立—尾插法 算法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)

4000

 {

   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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: