单向链表 头尾插法

来源:互联网 发布:淘宝运费险是怎么算的 编辑:程序博客网 时间:2024/05/11 01:50

单向链表  头尾插法

#include<iostream.h>#include<conio.h> struct node{   int data;   node *next;              };node *createlist(int );node *createlistinvert(int );void outputlist(node *head); int main(){  int n;  node *listhead=NULL;    cout<<"请输入节点数目: ";  cin>>n;  cout<<"**************下面请您输入"<<n<<"个整数*****************\n"<<endl;   if(n>0)    {         cout<<"      ***************尾差法********************\n"<<endl;         listhead=createlist(n);               outputlist(listhead);                         cout<<" \n\n    *****************头插法*********************\n"<<endl;          cout<<"**************下面请您输入"<<n<<"个整数*****************\n"<<endl;                  listhead=createlistinvert(n);                outputlist(listhead);      }       getch();   return 0; }//尾插法 node *createlist(int n){   node *temp=NULL,*tail=NULL,*head=NULL;      int num;      cout<<"请输入数据: ";    cin>>num;      head=new node;      if(head==NULL)     {        cout<<"内存分配不成功,重试吧!";                            return NULL;                               }             else    {       head->data=num;              head->next=NULL;       tail=head;                          }        for(int i=0;i<n-1;i++)      {               cin>>num;                  temp=new node;                  if(temp==NULL)           {              cout<<"内存分配不成功";                                        return head;                                           }                         else            {                temp->data=num;                temp->next=NULL;                tail->next=temp;                                tail=temp;                                   }                  }          return head;     }//头插法node *createlistinvert(int n){      node *temp=NULL,*head=NULL;            cout<<"请输入数据:";       int num;      cin>>num;             head=new node;            if(head==NULL)        {           cout<<"内存分配不成功!";             return NULL;                                                 }          else        {           head->data=num;                          head->next=NULL;                                 }        for(int i=0;i<n-1;i++)     {           cin>>num;                      temp=new node;                      if(temp==NULL)          {          cout<<"内存分配不成功!";                              return head;                                    }         else        {          temp->data=num;                 temp->next=head;                     head=temp;                      }        }    return head;  }    void outputlist(node *head) {      cout<<"List:   ";       node *curnode=head;            while(curnode)       {         cout<<curnode->data;         if(curnode->next)              cout<<"  -> ";                      curnode=curnode->next;               }             cout<<endl;           } 


 

原创粉丝点击