• Merge Two Sorted Lists


    问题:有序合并两个有序链表
    分析:归并排序的合并部分

    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode *helper=new ListNode(0);
            ListNode *head=helper;
            while(l1 && l2)
            {
                 if(l1->val<l2->val) helper->next=l1,l1=l1->next;
                 else helper->next=l2,l2=l2->next;
                 helper=helper->next;
            }
            if(l1) helper->next=l1;
            if(l2) helper->next=l2;
            return head->next;
        }
    };
    

      javascript

    /**
     * 题意:合并两条有序的链表
     * 分析:归并排序的链表形式
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var mergeTwoLists = function(l1, l2) {
       if(l1 == null) return l2;
        if(l2 == null) return l1;
        var head = null,iCur = null;
        if(l1.val<l2.val){
            iCur = l1;
            l1 = l1.next;
        }
        else {
            iCur = l2;
            l2 = l2.next;
        }
        head = iCur;
        while(l1!=null && l2!=null){
            if(l1.val < l2.val) {
                iCur.next = l1;
                l1 = l1.next;
            }else{
                iCur.next = l2;
                l2 = l2.next;
            } 
            iCur = iCur.next;
        }
        if(l1 == null) iCur.next = l2;
        if(l2 == null) iCur.next = l1;
        return head;
    }; 
    

      

  • 相关阅读:
    Docker 设置阿里云镜像
    Linux 安装Navicat Premium 15
    Ubuntu常用工具安装
    Docker安装MongoDB、MySQL、Jenkins、Gitlab、Nginx
    Ubuntu18.04修改apt-get源
    Spring定时任务
    Quartz学习总结
    cron表达式
    将VirtualBox里安装的虚拟机在后台运行方法(在状态栏隐藏窗口)
    npm小结
  • 原文地址:https://www.cnblogs.com/zsboy/p/3887229.html
Copyright © 2020-2023  润新知