将k个有序链表合并成一个有序链表

来源:互联网 发布:linux lvm 编辑:程序博客网 时间:2024/05/21 21:08

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
我的代码如下:

package 训练;import java.util.*;import org.w3c.dom.Node;public class 合并有序链表 {    public static void main(String[] args){        Scanner sc=new Scanner(System.in);        while(sc.hasNext()){            int n=Integer.parseInt(sc.nextLine());            ArrayList<ListNode> arr=new ArrayList<>();            String[] str=new String[n];            for(int i=0;i<n;i++){             str[i]=sc.nextLine();             String[] s=str[i].split(" ");            ListNode head=new ListNode(Integer.parseInt(s[0]));            ListNode node=head;            for(int j=1;j<s.length;j++){                node.next=new ListNode(Integer.parseInt(s[j]));                node=node.next;            }            arr.add(head);            }            ListNode chead=mergeKLists(arr);            while(chead!=null){                System.out.print(chead.val+" ");                chead=chead.next;            }            System.out.println();        }    }    static ListNode mergeKLists(ArrayList<ListNode> lists){         int n=lists.size();        if(n<=0)return null;        ListNode head=lists.get(0);        for(int i=1;i<n;i++){            head=merge2Lists(head,lists.get(i));        }        return head;    }    static ListNode merge2Lists(ListNode l1,ListNode l2){        ListNode head=null;        ListNode node=null;        while(l1!=null&&l2!=null){                if(head==null){                    if(l1.val<=l2.val){                    head=new ListNode(l1.val);                    l1=l1.next;                    }                    else{                        head=new ListNode(l2.val);                        l2=l2.next;                    }                    node=head;            }                else{                    if(l1.val<=l2.val){                        node.next=new ListNode(l1.val);                        node=node.next;                        l1=l1.next;                    }                    else{                        node.next=new ListNode(l2.val);                        node=node.next;                        l2=l2.next;                    }                }        }        while(l1!=null){            if(head==null){                head=new ListNode(l1.val);                node=head;                l1=l1.next;            }            else{            node.next=new ListNode(l1.val);            node=node.next;            l1=l1.next;            }        }        while(l2!=null){            if(head==null){                head=new ListNode(l2.val);                node=head;                l2=l2.next;            }            else{            node.next=new ListNode(l2.val);            node=node.next;            l2=l2.next;            }        }        return head;    }}

注意有的临界条件。

0 0