### 思路
1. 创建链表A和链表B,并将输入的元素插入到相应的链表中。
2. 创建一个新的链表C,用于存储合并后的结果。
3. 使用两个指针分别遍历链表A和链表B,将较小的元素插入到链表C中。
4. 如果一个链表遍历完了,将另一个链表剩余的元素插入到链表C中。
5. 输出链表A、链表B和链表C的元素。
### 伪代码
```
function createList(n):
initialize L as a new node
for i from 1 to n:
read element e
insert e into L at position i
return L
function mergeLists(A, B):
initialize C as a new node
initialize pointers pA to A->next, pB to B->next, pC to C
while pA is not null and pB is not null:
if pA->data <= pB->data:
insert pA->data into pC at position 1
move pA to the next node
move pC to the next node
else:
insert pB->data into pC at position 1
move pB to the next node
move pC to the next node
while pA is not null:
insert pA->data into pC at position 1
move pA to the next node
move pC to the next node
while pB is not null:
insert pB->data into pC at position 1
move pB to the next node
move pC to the next node
return C
function printList(L):
initialize pointer p to L->next
while p is not null:
print p->data
move p to the next node
main:
read nA
A = createList(nA)
read nB
B = createList(nB)
C = mergeLists(A, B)
print "List A:"
printList(A)
print "List B:"
printList(B)
print "List C:"
printList(C)
```
### C++代码
#include <iostream>
#include <malloc.h>
using namespace std;
#define ERROR 0
#define OK 1
#define ElemType int
typedef int Status;
typedef struct LNode {
int data;
struct LNode *next;
} LNode, *LinkList;
Status ListInsert_L(LinkList &L, int i, ElemType e) {
LinkList p, s;
p = L;
int j = 0;
while (p && j < i-1) {
p = p->next;
++j;
}
if (!p || j > i-1) return ERROR;
s = (LinkList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
Status ListDelete_L(LinkList &L, int i, ElemType &e) {
LinkList p, q;
p = L;
int j = 0;
while (p->next && j < i-1) {
p = p->next;
++j;
}
if (!(p->next) || j > i-1) return ERROR;
q = p->next;
p->next = q->next;
e = q->data;
free(q);
return OK;
}
LinkList createList(int n) {
LinkList L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
for (int i = 1; i <= n; ++i) {
int e;
cin >> e;
ListInsert_L(L, i, e);
}
return L;
}
LinkList mergeLists(LinkList A, LinkList B) {
LinkList C = (LinkList)malloc(sizeof(LNode));
C->next = NULL;
LinkList pA = A->next, pB = B->next, pC = C;
while (pA && pB) {
if (pA->data <= pB->data) {
ListInsert_L(pC, 1, pA->data);
pA = pA->next;
pC = pC->next;
} else {
ListInsert_L(pC, 1, pB->data);
pB = pB->next;
pC = pC->next;
}
}
while (pA) {
ListInsert_L(pC, 1, pA->data);
pA = pA->next;
pC = pC->next;
}
while (pB) {
ListInsert_L(pC, 1, pB->data);
pB = pB->next;
pC = pC->next;
}
return C;
}
void printList(LinkList L) {
LinkList p = L->next;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() {
int nA, nB;
cin >> nA;
LinkList A = createList(nA);
cin >> nB;
LinkList B = createList(nB);
LinkList C = mergeLists(A, B);
cout << "List A:";
printList(A);
cout << "List B:";
printList(B);
cout << "List C:";
printList(C);
return 0;
}