表A:1 3 5 7 9 10
表B:2 4 6 8 9 11 13
链表合并算:1 2 3 4 5 6 7 8 9 9 11 13
实现代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node, *LinkList;
LinkList CreateListTail(LinkList *L){
int i, num;
LinkList r, s;
*L = (LinkList)malloc(sizeof(Node));
r = *L;//头节点的值,找出最后一个
r->next = NULL;
while(1){
scanf("%d", &num);
if(num == 0){
break;
}else{
s = (LinkList)malloc(sizeof(Node));
s->data = num;
r->next = s;
r = s;
}
}
r->next = NULL;
return *L;
}
void PrintList(LinkList L){
LinkList r;
r = L->next;
while(r){//r指向最后一个节点时跳出
printf("%d ", r->data);
r = r->next;
}
printf("\n");
}
LinkList Merge(LinkList L1, LinkList L2){
LinkList L, r;
LinkList p1, p2;
L = (LinkList)malloc(sizeof(Node));//L为头节点,最后被返回出去
r = L;
p1 = L1->next;
p2 = L2->next;
while(p1 && p2){
if(p1->data < p2->data){
r->next = p1;
r = p1;
p1 = p1->next;
}else{
r->next = p2;
r = p2;
p2 = p2->next;
}
}
if(p1){
r->next = p1;
}else{
r->next = p2;
}
//清空表L1 l2
L1->next = NULL;
L2->next = NULL;
return L;
}
int main(){
LinkList L, L1, L2;
printf("请将数据输入两个链表中,以0为结尾\n");
printf("表A: ");
CreateListTail(&L1);
printf("表B: ");
CreateListTail(&L2);
L = Merge(L1, L2);
printf("链表合并算:");
PrintList(L);
}