C语言中的双向循环链表
2014-01-18 17:13
302 查看
单向链表的构建,大家应该不陌生
双向链表其实也一个道理
#include<stdio.h> #include<malloc.h> #define LEN sizeof(struct Node) typedef struct Node /*创建一个链式结构*/ { int num; struct Node*next;/*定义指针指向下一元素*/ }Tree; void CreatList() { Tree*head,*p1,*p2;/*一定要单独定义一个指针,作为链表的头*/ int i,n; head=NULL; /*建立一个空的链表*/ scanf("%d",&n); /*输入链表包含几个元素*/ for(i=1;i<=n;i++) { p1=(Tree*)malloc(LEN);/*动态申请内存进行链表的构建*/ scanf("%d",&p1->num); if(i==1) head=p1; else p2->next=p1; p2=p1; } p2->next=NULL;/*最后以NULL作为链表的结束*/ /*Ps:如果这里是 p2->next=head 那么这就是一个循环链表*/ }
双向链表其实也一个道理
#include<iostream> #include<stdio.h> #include<malloc.h> #define LEN sizeof(struct node) using namespace std; typedef struct node /*创建一个结构*/ { int data; node *prior,*next; /*用2个指针一个指向前方元素一个指向后方元素,构成双向链表*/ }List; List *p,*q,*head; void CreatList(int n) /*创建一个双向链表*/ { head=(List*)malloc(LEN); /*申请内存空间*/ head->data=0; p=head; for(int i=0;i<n;i++) { q=(List*)malloc(LEN); printf("请输入第%d/%d个元素:",i+1,n); scanf("%d",&q->data); p->next=q; /*将p的下一个元素指向新申请到的内存,构成链式结构*/ q->next=head; /*时刻使得最后的链尾指向开头,构成环状结构*/ q->prior=p; /*构成双向链表*/ p=q; /*移动节点继续链接*/ } head->prior=p; } void print() { p=head->next; printf("正向输出顺序为:\n"); while(p!=head) { printf("%d ",p->data); p=p->next; } printf("\n"); p=head->prior; printf("逆向输出顺序为:\n"); while(p!=head) { printf("%d ",p->data); p=p->prior; } } int main() { int n; scanf("%d",&n); CreatList(n); print(); return 0; }
相关文章推荐
- 给程序员介绍一些C++开源库
- 统计n个随机数(随机0~10),每出现一次就用*号在数字下面写一次*【c语言实现】
- 关于C语言中内嵌汇编指令的一个小细节
- c++中的while(cin)问题
- 在Win32下用C++实现多线程读写锁
- Logistic Regression(c++)源代码下载
- C指针原理(55)-C语言-pvm并行计算
- c语言递归的一些总结
- 第三次实现Logistic Regression(c++)_测试
- C++内存分配秘籍—new,malloc,GlobalAlloc详解
- 第三次实现Logistic Regression(c++)_实现(二)
- [POJ 1005] I Think I Need a Houseboat C++解题
- [POJ 1004] Financial Management C++解题
- [POJ 1003] Hangover C++解题
- code block与VC++下相对路径的不同写法
- [POJ 1002] 487-3279 C++解题报告
- [POJ 1001] Exponentiation C++解题报告 JAVA解题报告
- [POJ 1000] A+B Problem 经典水题 C++解题报告 JAVA解题报告
- LAPACK的C/C++接口及代码实例
- LAPACK的C/C++接口及代码实例