數據結構 P30 算法實現 鏈表的頭插法 尾插法

/*鏈表的正向建立—頭插法 & 鏈表的逆向建立—尾插法 算法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;
}
發佈了34 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章