1. 程式人生 > >尾插法的兩種方式的對比

尾插法的兩種方式的對比

#include <iostream>
#include <stdlib.h>

using namespace std;

#define DataType int
typedef struct Node
{
    DataType data;
    struct Node *link;
}LinkNode,*LinkList;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

void insertRear_ex(LinkList&
L,DataType& endTag) { if(L!=NULL) { LinkList first = (LinkList)L; while(first->link!=NULL) //在移動的過程中耗時 { first = first->link; } DataType val = 0; cin >> val; if(val == endTag) { return
; } else { LinkNode* node = new LinkNode; if(node!=NULL) { node->data = val; node->link = NULL; first->link = node; insertRear_ex(L,endTag); } } } } void
insertRear(LinkList &first,LinkNode *&last,DataType& endTag) { DataType val; cin>>val; if(val == endTag) { return ; } else { last = new LinkNode; if(last == NULL) { cerr<<"ALLOCATION ERROR"<<endl; exit(1); } else { last->data = val; last->link = NULL; insertRear(first,last->link,endTag); } } } void Print(LinkList &first) { LinkNode *p = first->link; cout<<"\nThe List is:" << endl; while(p != NULL) { cout<<p->data<<endl; p = p->link; } } int main(int argc, char *argv[]) { LinkList L = new LinkNode; if(L == NULL) { cerr<<"ALLOCATION ERROR"<<endl; exit(1); } cin>>L->data; L->link = NULL; insertRear(L,L->link,L->data); //連結串列的尾插法 //insertRear_ex(L,L->data); Print(L); return 0; }