zoukankan      html  css  js  c++  java
  • 力扣----7. 合并两个有序链表(JavaScript, Java实现)

    题目描述:

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

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4

    JavaScript实现:

    时间复杂度:O(n+m);

    空间复杂度:O(n+m);

    思路:递归

    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var mergeTwoLists = function(l1, l2) {
        if(!l1){
            return l2;
        }else if(!l2) {
            return l1;
        }else if(l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }else{
            l2.next = mergeTwoLists(l2.next, l1);
            return l2;
        }
    };

    非递归实现

     
    var mergeTwoLists = function(l1, l2) {
        let temp = res = new ListNode(-1);
        while(l1 && l2) {
            if (l1.val < l2.val) {
                temp.next = l1;
                l1 = l1.next
            }else {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }
        temp.next = l1 ? l1 : l2;
        return res.next;
    };

    java实现:

    待补充

  • 相关阅读:
    poj 3669 Meteor Shower
    poj 3232 Accelerator
    poj 2155 Matrix
    poj 3628 Bookshelf 2
    cf C. Maze
    cf B. Fox Dividing Cheese
    hdu Children’s Queue
    cf D. Broken Monitor
    cf C. Mittens
    cf B. Berland Bingo
  • 原文地址:https://www.cnblogs.com/manru75/p/13070274.html
Copyright © 2011-2022 走看看