#include<iostream>
using namespace std;
typedef struct ListNode {
int val;
struct ListNode* next;
}ListNode,*List;
void createList(List L, int n) {
ListNode* r = L;
for (int i = 0; i < n; i++) {
ListNode* p=new ListNode;
cin >> p->val;
p->next = NULL;
r->next = p;
r = r->next;
}
}
void printList(List L) {
ListNode* p = L;
while (p) {
cout << p->val<<" ";
p = p->next;
}
}
List mergeList(List L1, List L2) {
List L3 = new ListNode;
L3->next = NULL;
ListNode* p1 = L1->next;
ListNode* p2 = L2->next;
ListNode* p3 = L3;
while (p1 && p2) {
if (p1->val <= p2->val) {
p3->next = p1;
p1 = p1->next;
p3 = p3->next;
}
else {
p3->next = p2;
p2 = p2->next;
p3 = p3->next;
}
}
p3->next = p1 ? p1 : p2;
return L3->next;
}
int main() {
List L1=new ListNode;
L1->next = NULL;
List L2 = new ListNode;
int n1,n2;
cin >> n1;//链表L1个数
createList(L1,n1);
cin >> n2;
createList(L2, n2);
printList(mergeList(L1,L2));
system("pause");
return 0;
}
C++实现链表合并
于 2023-03-08 17:48:02 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)