zoukankan      html  css  js  c++  java
  • Merge Two Sorted Lists

    Question: Merge Two Sorted Lists

    Description: 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.


    Example:

    • Input: 1->2->4, 1->3->4
    • Output: 1->1->2->3->4->4

    Solution

     

     采用两个指针指向两个链表,比较指针对应节点的大小,较小的节点即为下一个节点,同时指针指向下一个节点;

    Solution Code

    /**
     * Definition for singly-linked list.
     * 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;
            // 两个链表都不为空
            ListNode *pMerge = nullptr;
            if(l1->val < l2->val){
                pMerge = l1;
                pMerge->next = mergeTwoLists(l1->next, l2);
            }
            else{
                pMerge = l2;
                pMerge->next = mergeTwoLists(l1, l2->next);
            }
            return pMerge;
        }
    };

    Reports: Runtime: 8 ms, faster than 89.04% of C++ online submissions for Merge Two Sorted Lists.

  • 相关阅读:
    C#发送邮件
    C# MD5加密
    html实现艺术字
    sql日期转换比较问题
    web 抓取
    NHibernate主要数据操作方法
    写日志
    备忘 sql分页
    自我介绍
    企业级应用和互联网应用的区别
  • 原文地址:https://www.cnblogs.com/iwangzhengchao/p/9985156.html
Copyright © 2011-2022 走看看