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

[cpp]  view plain  copy
 print ?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #define len sizeof(struct list)  
  4. struct list  
  5. {  
  6.     int x;  
  7.     struct list *pre,*next;  
  8. };  
  9. struct list * create()//创建链表并返回链表头的指针  
  10. {  
  11.     struct list *p,*p1,*head;  
  12.     head=p=(struct list *)malloc(len);  
  13.     p->pre=NULL;//1.第一个元素没有直接前驱  
  14.     scanf("%d",&p->x);  
  15.     int n=0;  
  16.     while(p->x!=-1)  
  17.     {  
  18.         if(n==0)  
  19.             n++;  
  20.         else//搞清楚就很明白看清。建议在纸上画画  
  21.             p1->next=p,p->pre=p1;  
  22.         p1=p;  
  23.         p=(struct list *)malloc(len);  
  24.         scanf("%d",&p->x);  
  25.     }  
  26.     p1->next=NULL;//2.最后一个元素没有直接后继  
  27. //  p1->next=head,head->pre=p1; //如果1 2 行代码删除 这样写 就是双向循环链表了吧 哈哈  
  28.     return head;  
  29. }  
  30. int main()  
  31. {  
  32.     struct list *l1;  
  33.     printf("请输入链表A,以-1结束:");  
  34.     l1=create();  
  35.     printf("\n");  
  36.     while(l1!=NULL)  
  37.     {  
  38.         printf("%d ",l1->x);  
  39.         l1=l1->next;  
  40.         if(l1!=NULL)  
  41.         printf("%d ",l1->pre->x);  
  42.     }  
  43.     printf("\n");  
  44.     return 0;  
  45. }  
[cpp]  view plain  copy
 print ?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #define len sizeof(struct list)  
  4. struct list  
  5. {  
  6.     int x;  
  7.     struct list *pre,*next;  
  8. };  
  9. struct list * create()//创建链表并返回链表头的指针  
  10. {  
  11.     struct list *p,*p1,*head;  
  12.     head=p=(struct list *)malloc(len);  
  13.     p->pre=NULL;//1.第一个元素没有直接前驱  
  14.     scanf("%d",&p->x);  
  15.     int n=0;  
  16.     while(p->x!=-1)  
  17.     {  
  18.         if(n==0)  
  19.             n++;  
  20.         else//搞清楚就很明白看清。建议在纸上画画  
  21.             p1->next=p,p->pre=p1;  
  22.         p1=p;  
  23.         p=(struct list *)malloc(len);  
  24.         scanf("%d",&p->x);  
  25.     }  
  26.     p1->next=NULL;//2.最后一个元素没有直接后继  
  27. //  p1->next=head,head->pre=p1; //如果1 2 行代码删除 这样写 就是双向循环链表了吧 哈哈  
  28.     return head;  
  29. }  
  30. int main()  
  31. {  
  32.     struct list *l1;  
  33.     printf("请输入链表A,以-1结束:");  
  34.     l1=create();  
  35.     printf("\n");  
  36.     while(l1!=NULL)  
  37.     {  
  38.         printf("%d ",l1->x);  
  39.         l1=l1->next;  
  40.         if(l1!=NULL)  
  41.         printf("%d ",l1->pre->x);  
  42.     }  
  43.     printf("\n");  
  44.     return 0;  
  45. }  

猜你喜欢

转载自blog.csdn.net/zzwdkxx/article/details/78848533