将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
(1)思路:递归
(2)代码
#include
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
} else if (l2 == nullptr) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
void output(ListNode *H){
ListNode *p = H;
while(p){
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
int main()
{
Solution sol;
ListNode* l1, *l2;
l1 = new ListNode(1);
l1->next = new ListNode(9);
l1->next->next = new ListNode(30);
l1->next->next->next = new ListNode(50);
l1->next->next->next->next = new ListNode(70);
l2 = new ListNode(2);
l2->next = new ListNode(4);
l2->next->next = new ListNode(6);
l2->next->next->next = new ListNode(30);
l2->next->next->next->next = new ListNode(50);
// console output 1
output(l1);
output(l2);
ListNode* ans = sol.mergeTwoLists(l1, l2);
// console output 2
output(ans);
return 0;
}