• (链表) 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.

    Example:

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

    中文:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
    -----------------------------------------------------------------------------------------------------------------
     
    这是一个链表操作的基础题,就是注意要分配一个空间来建立一个头结点
    C++代码
    /**
     * 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 *dummy = new ListNode(-1),*cur = dummy;  //* dummy是分配空间的,必须要分配空间,这个才能会得到一个结点,cur只是一个辅助结点(指针?)而已,并没有分配空间。
            while(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;  //就是如果l1和l2中长度更小的遍历完后,长度更大的剩下的就由cur链接它。
            return dummy->next;
        }
    };
  • 相关阅读:
    【摘录】面试官也许会这样问你....
    asp.net 面试题 【摘要】
    sql子查询
    c# 设计模式 之:简单工厂、工厂方法、抽象工厂之小结、区别
    C#编程:AOP编程思想
    EF Core 保存数据
    详解C#中的反射
    .Net Core RSA加解密,签名
    Sql Server帮助类
    c# DbfHelper 帮助类
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10703967.html
Copyright © 2020-2023  润新知