单向链表的创建与遍历(先进先出和先进后出)
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; }
相关文章推荐
- [C/C++]反转链表
- C#实现基于链表的内存记事本实例
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- C++实现简单的学生管理系统
- Linux内核链表实现过程
- C++链表倒序实现方法
- C#通过链表实现队列的方法
- C#实现的简单链表类实例
- 找出链表倒数第n个节点元素的二个方法
- Java数据结构之简单链表的定义与实现方法示例
- C语言单循环链表的表示与实现实例详解
- C++实现的链表类实例
- PHP小教程之实现链表
- PHP中模拟链表和链表的基本操作示例
- C语言双向链表的表示与实现实例详解
- js链表操作(实例讲解)
- C语言实现输出链表中倒数第k个节点
- C++语言实现线性表之链表实例
- STL list链表的用法详细解析
- C语言创建链表错误之通过指针参数申请动态内存实例分析