📄 main.cpp
字号:
/************************************************************************************
41. (合并链表) 已知两个链表 AN={a1,a2,...an}, BN={b1,b2,...bm}, 将其合并
为一个链表 CN={a1,b1,a2,b2,...}
*************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#define MAX_LEN 30 //链表的最大长度
enum{A=1,B}; //链表类型A,B
//链表节点
typedef struct tagNode
{
int data;
tagNode *next;
}Node;
//创建链表,A为奇数,B为偶数
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);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -