• Leecode no.23 合并K个升序链表


    package com.example.demo.leecode;

    /**
    * 合并K个升序链表
    * @Date 2020/12/15
    * @author Tang
    *
    * 给你一个链表数组,每个链表都已经按升序排列。
    * 请你将所有链表合并到一个升序链表中,返回合并后的链表。
    */
    public class MergeKSortedLists {

    public ListNode execute(ListNode[] lists){
    if(lists.length == 0){
    return null;
    }
    ListNode firstNode = lists[0];

    for(int i = 1; i < lists.length; i++){
    firstNode = mergeTwoList(firstNode, lists[i]);
    }

    return firstNode;
    }

    private ListNode mergeTwoList(ListNode l1, ListNode l2){
    ListNode first;
    ListNode end;
    if(l1.val <= l2.val){
    first = l1;
    l1 = l1.next;
    }else{
    first = l2;
    l2 = l2.next;
    }

    end = first;

    //循环排序成一条链表 直到其中一条到头了
    while(l1 != null && l2 != null){
    if(l1.val <= l2.val){
    end.next = l1;
    end = l1;
    l1 = l1.next;
    }else{
    end.next = l2;
    end = l2;
    l2 = l2.next;
    }

    }

    while(l1 != null){
    end.next = l1;
    end = l1;
    l1 = l1.next;
    }

    while(l2 != null){
    end.next = l2;
    end = l2;
    l2 = l2.next;
    }

    return first;
    }

    public static void main(String[] args) {

    ListNode l1 = new ListNode(1);
    ListNode l2 = new ListNode(2);
    ListNode l3 = new ListNode(3);
    ListNode l4 = new ListNode(5);

    ListNode l5 = new ListNode(2);
    ListNode l6 = new ListNode(4);
    ListNode l7 = new ListNode(8);
    ListNode l8 = new ListNode(9);

    ListNode l9 = new ListNode(2);
    ListNode l10 = new ListNode(3);
    ListNode l11 = new ListNode(4);
    ListNode l12 = new ListNode(5);

    l1.next = l2; l2.next = l3; l3.next = l4;
    l5.next = l6; l6.next = l7; l7.next = l8;
    l9.next = l10; l10.next = l11; l11.next = l12;

    ListNode[] list = {l1, l5, l9};
    ListNode execute = new MergeKSortedLists().execute(list);

    System.out.println(execute.val);
    while(execute.hasNext()){
    execute = execute.next;
    System.out.println(execute.val);

    }

    }
    }

    class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) {
    this.val = val;
    }
    ListNode(int val, ListNode next) {
    this.val = val;
    this.next = next;
    }
    boolean hasNext(){
    return next != null;
    }

    }
  • 相关阅读:
    nginx 部署
    win 7 系统ie浏览器升级11版本后,f12功能不可用的问题
    selenium 调用键盘按键
    selenium + python 环境搭建
    解决word2013老是打开未响应情况
    win7 64位备份时, 无法启动服务,0x80070422
    个人学习网站收集
    矩形后旋转后顶点坐标的求解
    Acrobat_8_Pro_SC 激活老是提示你输入的授权码无效
    DLL用def定义文件来导出重载函数(转)
  • 原文地址:https://www.cnblogs.com/ttaall/p/14137691.html
Copyright © 2020-2023  润新知