zoukankan      html  css  js  c++  java
  • [LeetCode] 21 Merge Two Sorted Lists 合并两个有序链表

    [LeetCode]21 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

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

    题意

    将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

    题解

    新构建一个链表,然后有序插入即可,注意,当一个链表为空时,直接将另一个链表插在后面即可。

    代码

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

    ---恢复内容结束---

  • 相关阅读:
    spring的常用配置
    aop切入点表达式
    代理模式
    hibernate的常用配置
    正则表达式
    Java配置
    性能提升
    创建vue3 项目
    manjaro
    单调队列
  • 原文地址:https://www.cnblogs.com/caomingpei/p/10624965.html
Copyright © 2011-2022 走看看