思想:
用两个临时指针p,q分别扫描链表L1和L2,比较大小,将小的那个利用尾插法插入新的链表L,循环结束,继续检查较长链表是否有剩余元素,继续利用尾插法将剩余元素插入L
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkNode {
int data;
struct LinkNode* next;
}*LinkList,LinkNode;
void InitLinkList(LinkList &L) {
L = (LinkList)malloc(sizeof(LinkNode));
L->next = NULL;
}
void Create(LinkList &L,int len) {
int a;
LinkNode* r;
r = L;
for (int i = 0; i <len ; i++) {
scanf_s("%d", &a);
LinkNode* p = (LinkList)malloc(sizeof(LinkNode));
p->next = NULL;
p->data = a;
r->next = p;
r = p;
}
}
void Combine(LinkList &L1,LinkList &L2,LinkList &L) {//合并两个链表的函数
LinkNode* p, * q,*r;
p = L1->next;
q = L2->next;
r = L;
while (p && q) {
if (p->data > q->data) {
r->next = q;
r = q;
q = q->next;
}
else {
r->next = p;
r = p;
p = p->next;
}
}
while (p) {
r->next = p;
r = p;
p = p->next;
}
while (q) {
r->next = q;
r = q;
q = q->next;
}
}
void Print(LinkList L) {
LinkNode* p=L;
while (p!=NULL) {
p = p->next;
printf("%d ", p->data);
}
printf("\n");
}
int main() {
LinkList L1,L2,L;
int len1,len2;
scanf_s("%d",&len1 );
InitLinkList(L1);
Create(L1, len1);
InitLinkList(L);
scanf_s("%d", &len2);
InitLinkList(L2);
Create(L2, len2);
Combine(L1, L2, L);
Print(L);
return 0;
}