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.

  • 相关阅读:
    MongoDB
    Mac下将Python2.7改为Python3
    Kafka
    Server 基础概念 备忘
    应用内支付
    Sign in with apple
    Linux三剑客grep/sed/awk
    React-Native中使用到的一些JS特性
    Date Picker控件:
    Picker View控件:
  • 原文地址:https://www.cnblogs.com/iwangzhengchao/p/9985156.html
Copyright © 2011-2022 走看看