用c++将两个升序链表合并成一个升序链表
时间: 2023-10-16 18:11:09 浏览: 104
```c++
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* head = NULL;
if(l1->val < l2->val) {
head = l1;
head->next = mergeTwoLists(l1->next, l2);
}
else {
head = l2;
head->next = mergeTwoLists(l1, l2->next);
}
return head;
}
int main() {
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(2);
l1->next->next = new ListNode(4);
ListNode* l2 = new ListNode(1);
l2->next = new ListNode(3);
l2->next->next = new ListNode(4);
ListNode* l3 = mergeTwoLists(l1, l2);
while(l3 != NULL) {
cout << l3->val << " ";
l3 = l3->next;
}
return 0;
}
```
阅读全文