练习41

来源:互联网 发布:游戏编程语言 编辑:程序博客网 时间:2024/04/28 13:01
 
  1. /************************************************************************************
  2.  41. (合并链表) 已知两个链表 AN={a1,a2,...an}, BN={b1,b2,...bm}, 将其合并
  3.  为一个链表 CN={a1,b1,a2,b2,...}
  4. *************************************************************************************/
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <time.h>
  8. #include <malloc.h>
  9. #define MAX_LEN 30 //链表的最大长度
  10. enum{A=1,B}; //链表类型A,B
  11. //链表节点
  12. typedef struct tagNode
  13. {
  14.     int data;
  15.     tagNode *next;
  16. }Node;
  17. //创建链表,A为奇数,B为偶数
  18. Node* CreateLink(int type)
  19. {
  20.     int n;
  21.     Node *head=NULL,*tail=NULL,*cur=NULL; 
  22.     n = rand()%MAX_LEN;
  23.     int i;
  24.     for(i=0; i<n; i++)
  25.     {
  26.         cur = (Node*)malloc(sizeof(Node));
  27.         cur->data = 2*i+type;
  28.         cur->next = NULL;
  29.         if(!head)
  30.             head = tail = cur;
  31.         else 
  32.         {
  33.             tail->next = cur;
  34.             tail = tail->next;
  35.         }
  36.     }
  37.     return head;
  38. }
  39. //合并链表
  40. Node* CombineLink(Node *la, Node *lb)
  41. {
  42.     Node *cur=NULL;
  43.     Node *s,*t;
  44.     if(!la)
  45.         return lb;
  46.     if(!lb)
  47.         return la;
  48.     s = la,t = lb;
  49.     while(s && t)
  50.     {
  51.         if(!cur)
  52.             cur = s;
  53.         else 
  54.         {
  55.             cur->next = s;
  56.             cur = cur->next;
  57.         }
  58.         s = s->next;
  59.         cur->next = t;
  60.         cur = cur->next;
  61.         t = t->next;
  62.     }
  63.     (s)?(cur->next = s):(cur->next = t);
  64.     return la;
  65. }
  66. //打印链表数据
  67. void PrintLink(Node *l)
  68. {
  69.     while(l)
  70.     {
  71.         printf("%3d",l->data);
  72.         l = l->next;
  73.     }
  74.     printf("/n");
  75. }
  76. void main()
  77. {
  78.     Node *la,*lb,*lc;
  79.     srand(time(0));
  80.     la = CreateLink(A);
  81.     PrintLink(la);
  82.     lb = CreateLink(B);
  83.     PrintLink(lb);
  84.     lc = CombineLink(la,lb);
  85.     PrintLink(lc);
  86. }
原创粉丝点击