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

来源:互联网 发布:python tuple 和 array 编辑:程序博客网 时间:2024/04/28 13:30

/*链表的正向建立—头插法 & 链表的逆向建立—尾插法 算法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;
}
原创粉丝点击