已知两个已排序链表头节点指针l1与l2,将这两个链表合并,合并后认为有序的,返回合并后的头节点。
思路:
比较l1和l2指向的节点,将较小的节点插入到pre指针后,并向前移动较小节点对应的指针。
#include <stdio.h>
struct ListNode
{
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
Solution() {}
~Solution() {}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode temp_head(0);
ListNode* pre = &temp_head;
while (l1 && l2)
{
if (l1->val < l2->val)
{
pre->next = l1;
l1 = l1->next;
}
else
{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
if (l1)
{
pre->next = l1;
}
if (l2)
{
pre->next = l2;
}
return temp_head.next;
}
};
int main()
{
ListNode a(1);
ListNode b(4);
ListNode c(6);
ListNode d(0);
ListNode e(5);
ListNode f(7);
a.next = &b;
b.next = &c;
d.next = &e;
e.next = &f;
Solution solve;
ListNode* head = solve.mergeTwoLists(&a, &d);
while (head)
{
printf("%d\n", head->val);
head = head->next;
}
return 0;
}
运行结果:
0
1
4
5
6
7
来源:CSDN
作者:Gianna K
链接:https://blog.csdn.net/weixin_44208324/article/details/104524647