您的位置:首页 > 其它

单向链表的创建与遍历(先进先出和先进后出)

2016-03-12 19:12 711 查看
先进先出:输入任意一串不为零的数,并建立和前一方向不同的单向链表,并按照先进先出的原则依次输出。

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef struct node
{
int data;
struct node *next;
}NODE,*LinkList;
LinkList Createlist()
{
LinkList h,p,q;
p=(NODE *)malloc(sizeof(NODE));
h=p;
int x;
cin>>x;
if(x!=0)
{
q=(NODE *)malloc(sizeof(NODE));
q->data=x;
p->next=q;
p=q;
}
else if(x==0)
return NULL;
cin>>x;
while(x!=0)
{
q=(NODE *)malloc(sizeof(NODE));
q->data=x;
p->next=q;
p=q;
cin>>x;
}
q->next=NULL;
return h;
}
void outputlist(LinkList h)
{
LinkList q=h;
while(q!=NULL||q->next!=NULL)
{
q=q->next;
cout<<q->data<<endl;
}
}
void freelist(LinkList h)
{
LinkList q=h,p;
while(q!=NULL||q->next!=NULL)
{
p=q;
q=q->next;
free(p);
}
}
int main()
{
NODE *head;
head = Createlist();
outputlist(head);
freelist(head);
return 0;
}


先进后出:输入任意一串不为零的数,并建立和前一方向不同的单向链表,并按照先进后出的原则依次输出。

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef struct node
{
int data;
struct node *next;
} Node,*LinkList;
LinkList Createlist()
{
LinkList h,p;
int x;
cin>>x;
if(x!=0)
{
h=(Node *)malloc(sizeof(Node));
h->data=x;
h->next=NULL;
}
else if(x==0)
return NULL;
cin>>x;
while(x!=0)
{
p=(Node *)malloc(sizeof(Node));
p->data=x;
p->next=h;
h=p;
cin>>x;
}
return h;
}
void outputlist(LinkList head1)
{
LinkList p=head1;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
void free(LinkList head1)
{
LinkList p=head1;
LinkList q=NULL;
while(p!=NULL)
{
q=p;
p=p->next;
free(q);
}
}
int main()
{
LinkList head;
head=Createlist();
outputlist(head);
free(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表