#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;
}
尾插法的两种方式的对比
最新推荐文章于 2024-05-01 00:58:01 发布