import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类ArrayList * @return ListNode类 */ public ListNode mergeKLists (ArrayList<ListNode> lists) { // write code here // 解题思路合并多个升序链表和合并2个升序链表思路一致,就是多了一层循环 if (lists == null || lists.size() == 0) { return null; } if (lists.size() == 1) { return lists.get(0); } ListNode n1 = lists.get(0); for (int i = 1; i < lists.size(); i++) { n1= merge(n1,lists.get(i)); } return n1; } private ListNode merge(ListNode pHead1, ListNode pHead2) { ListNode cur = new ListNode(-1); ListNode root = cur; while (pHead1 != null || pHead2 != null) { if (pHead1 == null) { cur.next = pHead2; break; } if (pHead2 == null) { cur.next = pHead1; break; } int val1 = pHead1.val; int val2 = pHead2.val; if(val1 >val2){ cur.next = pHead2; pHead2 = pHead2.next; }else{ cur.next = pHead1; pHead1 = pHead1.next; } cur = cur.next; } return root.next; } }