1 题目
题目:合并两个排序链表(Merge Two Sorted Lists)
描述:将两个排序(升序)链表合并为一个新的升序排序链表。
lintcode题号——165,难度——easy
样例1:
输入: list1 = null, list2 = 0->3->3->null
输出: 0->3->3->null
样例2:
输入: list1 = 1->3->8->11->15->null, list2 = 2->null
输出: 1->2->3->8->11->15->null
2 解决方案
2.1 思路
对有序链表的合并,从两个链表头开始,对比两个链表的表头,将较小的放入新链表,然后较小的表头向后移动,以此类推直到其中一个为空,再将剩下不空的链表直接连接在新链表的尾部即可完成排序。
2.2 时间复杂度
若两个链表的长度分别为m和n,时间复杂度为O(m + n)。
2.3空间复杂度
空间复杂度为O(1)。
3 源码
细节:
- 对比两个表头,将较小的放入新链表,直到其中一个为空。
- 最后将不空的链表直接连接到新链表尾部即可。
链表的拼接不需要使用循环,直接将两个链表头尾相接即可完成拼接。
C++版本:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
if (l1 == nullptr)
{
return l2;
}
if (l2 == nullptr)
{
return l1;
}
ListNode dummyNode(0);
ListNode * cur = &dummyNode;
while (l1 != nullptr && l2 != nullptr)
{
if (l1->val < l2->val)
{
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else
{
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
// 链表拼接不需要使用循环,直接给next指针赋值即可
if (l1 != nullptr)
{
cur->next = l1;
}
if (l2 != nullptr)
{
cur->next = l2;
}
return dummyNode.next;
}