zoukankan      html  css  js  c++  java
  • LeetCode【21】 Merge Two Sorted Lists

    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.

    AC代码如下:

    ListNode* merge(ListNode* l1,ListNode* l2,int f1,int f2)
    {
        if(f1<f2)
            return merge(l2,l1,f2,f1);
        //f1>=f2
        //Insert l1 into l2
        ListNode* tmp1=l1;
        ListNode* tmp2=l2;
        for(;tmp2->next!=NULL;)
        {
            if(tmp1!=NULL && tmp1->val>=tmp2->val && tmp1->val<=tmp2->next->val )
            {
                ListNode* newNode = new ListNode(tmp1->val);
                newNode->next = tmp2->next;
                tmp2->next = newNode;
                tmp1 = tmp1->next;
            }
            else
                tmp2=tmp2->next;
        }
        tmp2->next = tmp1;
        return l2;
    }
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        if(l1 == NULL && l2 == NULL)
            return NULL;
        else if(l1 == NULL)
            return l2;
        else if(l2 == NULL)
            return l1;
        else
        {
            int len1=0,len2=0;
            return merge(l1,l2,l1->val,l2->val);
        }

    思路比较简单,考虑到在链表头插入元素稍麻烦一点,于是比较两个链表第一个值大小,将较大值所在的链表插入到较小值所在的链表。

  • 相关阅读:
    软件开发术语
    网络规划与设计
    MPLS LDP协议
    MPLS 基础
    CallAfter
    LongRunningTasks
    Non-blocking GUI
    WorkingWithThreads
    Python: Running Ping, Traceroute and More
    wxPython and Threads
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4445752.html
Copyright © 2011-2022 走看看