合并两个有序链表-算法详细法分析

题目:合并两个有序链表

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

示例:

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


 package com.test.day6_10;
 
 /**
 
  * @author cosefy
 
  * @date 2020/6/10
    */
    public class MergeTwoLists {
    public static void main(String[] args) {
        ListNode l1 =new ListNode(1,new ListNode(3,new ListNode(4,null)));//1-3-4
        ListNode l2 =new ListNode(1,new ListNode(2,new ListNode(4,null)));//1-2-4
        ListNode l3 = mergerTwoLists(l1, l2);
        ListNode.showList(l3);
 
    }
ListNode类:
public class ListNode {
    int val;
    ListNode next;

    ListNode(){}
    ListNode(int val){
        this.val = val;
    }


    public static void showList(ListNode node) {
        while (node!=null) {
            System.out.print("ListNode: "+ "val="+node.val+" ");
            node= node.next;
        }
    }

    ListNode(int val, ListNode next){
        this.val=val;
        this.next=next;
    }
}
解法:常规解法

思路:当两个链表都不为空时,依次寻找最小结点,链接,当其中一链表遍历结束,把另一链表的剩余部分链接上。
分析:最坏时间复杂度O(n+m),空间复杂度O(1)

public static ListNode mergerTwoLists(ListNode l1, ListNode l2)  {
    ListNode l3= new ListNode(0,null);
    ListNode mark = l3;
    while(l1!=null && l2!=null){
        if (l1.val < l2.val) {
            l3.next = l1;
            l1 = l1.next;
        } else {
            l3.next=l2;
            l2 = l2.next;
        }
        l3= l3.next;
    }
    if (l1 != null) {
        l3.next=l1;
    }
    if (l2 != null) {
        l3.next=l2;
    }
    return mark.next;
}
}
结果:ListNode: val=1 ListNode: val=1 ListNode: val=2 ListNode: val=3 ListNode: val=4 ListNode: val=4
posted @ 2020-06-10 16:43  cosefy  阅读(1223)  评论(0编辑  收藏  举报