加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
2747.cpp 1.90 KB
一键复制 编辑 原始数据 按行查看 历史
张宬浩 提交于 2021-11-09 14:10 . modified comment
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkList;
void MergeList(LinkList a, LinkList b);
int main() {
int T = 0;
int t = 0;
scanf("%d", &T);
for( t = 0; t < T; t++ ) { // Loop for T times
int lenA = 0, lenB = 0;
int i = 0;
scanf("%d", &lenA);
scanf("%d", &lenB);
//Create La
LinkList La;
La = (LinkList)malloc(sizeof(Node));
La->next = NULL;
for ( i = 0; i < lenA; i++ ) {
Node* p = NULL;
p = (LinkList)malloc(sizeof(Node));
p->next = La->next;
La->next = p;
}
//Create Lb
LinkList Lb;
Lb = (LinkList)malloc(sizeof(Node));
Lb->next = NULL;
for ( i = 0; i < lenB; i++ ) {
Node* p = NULL;
p = (LinkList)malloc(sizeof(Node));
p->next = Lb->next;
Lb->next = p;
}
//Input La
LinkList ptrA = La;
for ( i = 0; i < lenA; i++) {
ptrA = ptrA->next;
scanf("%d", &(ptrA->data));
}
//Input Lb
LinkList ptrB = Lb;
for ( i = 0; i < lenB; i++) {
ptrB = ptrB->next;
scanf("%d", &(ptrB->data));
}
//Merge Lb to La
MergeList(La, Lb);
//Generate Lc
LinkList Lc = La;
//Print Lc
LinkList p = Lc->next;
for ( i = 0; i < (lenA + lenB); i++ ) {
printf("%d",p->data);
p = p->next;
if ( i == lenA + lenB - 1 ) {
printf ("\n");
}
else printf(" ");
}
}
return 0;
}
void MergeList(LinkList a, LinkList b) {
LinkList NewP, pa, pb;
NewP = a;//Travel through new list
pa = a->next;// Travel through La
pb = b->next;// Travel through Lb
while (pa && pb)
{
//Add a node from La
NewP->next = pa;
pa = pa->next;
NewP = NewP->next;
if (pa==0) break;//stop, if La is empty
//Add a node from Lb
NewP->next = pb;
pb = pb->next;
NewP = NewP->next;
if (pb==0) break;//stop, if Lb is empty
}
NewP->next = pa ? pa : pb;//Append the rest
free(b); //Free the header of Lb
return;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化