7-51-两个有序链表序列的合并-编程题
程序员文章站
2022-06-07 21:44:34
...
解题代码
#include<stdio.h>
#include<stdlib.h>
typedef struct Node* List;
struct Node {
int Data;
List Next;
};
List Insert(List L, int temp);
void Merge(List head1, List head2, List head3);
void Print(List head);
int main()
{
List head1 = (List)malloc(sizeof(struct Node));
head1->Next = NULL;
List head2 = (List)malloc(sizeof(struct Node));
head2->Next = NULL;
List L1 = head1, L2 = head2;
int temp;
while (1) {
scanf("%d", &temp);
if (temp == -1) break;
else L1=Insert(L1, temp);
}
while (1) {
scanf("%d", &temp);
if (temp == -1) break;
else L2=Insert(L2, temp);
}
List head3 = (List)malloc(sizeof(struct Node));
head3->Next = NULL;
Merge(head1, head2, head3);
Print(head3);
return 0;
}
List Insert(List L, int temp) {
List add = (List)malloc(sizeof(struct Node));
add->Data = temp;
add->Next = NULL;
L->Next = add;
L = add;
return add;
}
void Merge(List head1, List head2, List head3) {
List t1 = head1->Next;
List t2 = head2->Next;
List t3 = head3;
if (!t1) {
if (!t2) {
head3->Next = NULL;
}
else {
head3->Next = t2;
}
}
else if(!t2){
head3->Next = t1;
}
else {
while (t1 && t2) {
if (t1->Data <= t2->Data) {
t3 = Insert(t3, t1->Data);
t1 = t1->Next;
}
else {
t3 = Insert(t3, t2->Data);
t2 = t2->Next;
}
}
while (t1) {
t3 = Insert(t3, t1->Data);
t1 = t1->Next;
}
while (t2) {
t3 = Insert(t3, t2->Data);
t2 = t2->Next;
}
}
}
void Print(List head) {
if (!head->Next) {
printf("NULL");
}
else {
List t = head->Next;
int flag = 1;
while (t) {
if (flag) flag = 0;
else printf(" ");
printf("%d", t->Data);
t = t->Next;
}
}
}
测试结果
问题整理
1.注意/不是NULL/的判断条件。