练习41
来源:互联网 发布:游戏编程语言 编辑:程序博客网 时间:2024/04/28 13:01
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <malloc.h>
- #define MAX_LEN 30 //链表的最大长度
- enum{A=1,B};
- typedef struct tagNode
- {
- int data;
- tagNode *next;
- }Node;
- Node* CreateLink(int type)
- {
- int n;
- Node *head=NULL,*tail=NULL,*cur=NULL;
- n = rand()%MAX_LEN;
- int i;
- for(i=0; i<n; i++)
- {
- cur = (Node*)malloc(sizeof(Node));
- cur->data = 2*i+type;
- cur->next = NULL;
- if(!head)
- head = tail = cur;
- else
- {
- tail->next = cur;
- tail = tail->next;
- }
- }
- return head;
- }
- Node* CombineLink(Node *la, Node *lb)
- {
- Node *cur=NULL;
- Node *s,*t;
- if(!la)
- return lb;
- if(!lb)
- return la;
- s = la,t = lb;
- while(s && t)
- {
- if(!cur)
- cur = s;
- else
- {
- cur->next = s;
- cur = cur->next;
- }
- s = s->next;
- cur->next = t;
- cur = cur->next;
- t = t->next;
- }
- (s)?(cur->next = s):(cur->next = t);
- return la;
- }
- void PrintLink(Node *l)
- {
- while(l)
- {
- printf("%3d",l->data);
- l = l->next;
- }
- printf("/n");
- }
- void main()
- {
- Node *la,*lb,*lc;
- srand(time(0));
- la = CreateLink(A);
- PrintLink(la);
- lb = CreateLink(B);
- PrintLink(lb);
- lc = CombineLink(la,lb);
- PrintLink(lc);
- }