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

    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.

    由于l1,l2是已排序的,因此l1->val,l2->val分别代表了两个链表的最小值。

    逐个最小值取出,装入新链表。

    当一个链表为空时,另一个链表整个链入。

    /**
     * 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) {
            ListNode* newhead = new ListNode(-1);
            ListNode* tail = newhead;
            while(l1 != NULL && l2 != NULL)
            {
                if(l1->val <= l2->val)
                {
                    tail->next = l1;
                    l1 = l1->next;
                }
                else
                {
                    tail->next = l2;
                    l2 = l2->next;
                }
                tail = tail->next;
            }
            if(l1 != NULL)
                tail->next = l1;
            if(l2 != NULL)
                tail->next = l2;
            return newhead->next;
        }
    };

  • 相关阅读:
    angular4浏览器兼容问题
    angular4组件生命周期
    angular4路由
    CDH 安装配置指南(Tarball方式)
    nginx-1.14.0安装
    redis-3.0.6安装
    CDH安装kafka
    CDH配置JAVA_HOME
    ntp集群时间同步
    VMware联网
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4155184.html
Copyright © 2011-2022 走看看