创建一个双向链表或双向循环链表

来源:互联网 发布:mac os 10.10.5 编辑:程序博客网 时间:2024/05/23 18:34
#include <stdio.h>#include <stdlib.h>#define len sizeof(struct list)struct list{int x;struct list *pre,*next;};struct list * create()//创建链表并返回链表头的指针{struct list *p,*p1,*head;head=p=(struct list *)malloc(len);p->pre=NULL;//1.第一个元素没有直接前驱scanf("%d",&p->x);int n=0;while(p->x!=-1){if(n==0)n++;else//搞清楚就很明白看清。建议在纸上画画p1->next=p,p->pre=p1;p1=p;p=(struct list *)malloc(len);scanf("%d",&p->x);}p1->next=NULL;//2.最后一个元素没有直接后继//p1->next=head,head->pre=p1; //如果1 2 行代码删除 这样写 就是双向循环链表了吧 哈哈return head;}int main(){struct list *l1;printf("请输入链表A,以-1结束:");l1=create();printf("\n");while(l1!=NULL){printf("%d ",l1->x);l1=l1->next;if(l1!=NULL)printf("%d ",l1->pre->x);}printf("\n");return 0;}


 

0 0
原创粉丝点击