常考数据结构与算法:合并k个已排序的链表

题目描述

合并\ k k 个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。 

示例1

输入

[{1,2,3},{4,5,6,7}]

返回值

{1,2,3,4,5,6,7}
import java.util.ArrayList;

public class MergeKLists {
    public static void main(String[] args) {
        // [{-1,1},{-3,1,4},{-2,-1,0,2}]
        ListNode a0 = new ListNode(-1);
        ListNode b0 = new ListNode(1);
        a0.next = b0;

        ListNode a = new ListNode(-3);
        ListNode b = new ListNode(1);
        ListNode c = new ListNode(4);
        a.next = b;
        b.next = c;

        ListNode a1 = new ListNode(-2);
        ListNode b1 = new ListNode(-1);
        ListNode c1 = new ListNode(0);
        ListNode d1 = new ListNode(2);
        a1.next = b1;
        b1.next = c1;
        c1.next = d1;
        ArrayList<ListNode> lists = new ArrayList<>();
        lists.add(a0);
        lists.add(a);
        lists.add(a1);

        MergeKLists k = new MergeKLists();
        ListNode result = k.mergeKLists(lists);
        k.showListNode(result);
    }

    public static void showListNode(ListNode result){
        while(null != result){
            System.out.println(result.val);
            result = result.next;
        }
    }

    public ListNode mergeKLists(ArrayList<ListNode> lists) {

        if(null == lists){
            return null;
        }

        ListNode newHead = new ListNode(-1);
        ListNode first = null;
        ListNode second = null;
        ListNode temp = null;
        for(ListNode listNode : lists){
         // 循环每一个链表,两两合并成一个新的链表,用合并好的新的链表用作和下一次循环的链表比较
            second = listNode;

                first = newHead.next;
                temp = newHead;
                while(null != first && null != second){
                    if(first.val < second.val){
                        temp.next = first;
                        temp = first;
                        first = first.next;
                    }else{
                        temp.next = second;
                        temp = second;
                        second = second.next;
                    }
                }

                if(null != first){
                    temp.next = first;
                }

                if(null != second){
                    temp.next = second;
                }
            }


        return newHead.next;
    }
}


class ListNode {
    int val;
    ListNode next = null;

    ListNode() {
    }

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

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/113868883
今日推荐