[leetcode] Merge Two Sorted Lists

本文介绍两种合并两个有序链表的方法:一种通过不断插入节点,另一种采用类似归并排序的思路。这两种方法的时间复杂度均为O(m+n)。

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

我这里有两个思路,代码都挺简洁的,一个是把其中一个链表中的数据全部插入到另一个链表中去;另一个是采用归并排序的思路,时间复杂度都是0(m+n)

下面分别给出两个思路的代码:

下面这个是采用将一个链表中的节点不断的插入到另一个链表中去

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(l1==NULL)
            return l2;
        if(l2==NULL)
            return l1;
        ListNode* temp=new ListNode(0);
        temp->next=l1;
        l1=temp;
        ListNode*p,*q;
        p=l1,q=l1->next;
        ListNode*m=l2;
        for(; l2 ;l2=m){
            m=l2->next;
            for( ; q && l2->val>q->val ; p=p->next,q=q->next);
            l2->next=q;
            p->next=l2;
            p=p->next;
        }
        ListNode* ret=temp->next;
        delete temp;
        return ret;
    }
};


下面这个采用归并排序的思路

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode *q1,*q2,*cur;
        ListNode *head=new ListNode(-1);
        head->next=NULL,cur=head;
        for( ; l1 && l2 ; ){
            if(l1->val<l2->val){
                cur->next=l1;
                l1=l1->next;
            }else{
                cur->next=l2;
                l2=l2->next;
            }
            cur=cur->next;
        }
        cur->next= l1?l1:l2;
        cur=head->next;
        delete head;
        return cur;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值