题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
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类 */ private ListNode Merge (ListNode pHead1, ListNode pHead2) { // write code here if (pHead1 == null) { return pHead2; } else if (pHead2 == null) { return pHead1; } ListNode dummyNode = new ListNode(-1001); // 用超出范围的哑节点 ListNode cur = dummyNode; ListNode cur1 = pHead1; ListNode cur2 = pHead2; while (true) { if (cur1.val <= cur2.val) { cur.next = cur1; cur = cur.next; cur1 = cur1.next; } else { cur.next = cur2; cur = cur.next; cur2 = cur2.next; } if (cur1 == null) { cur.next = cur2; break; } else if (cur2 == null) { cur.next = cur1; break; } } return dummyNode.next; } public ListNode mergeKLists (ArrayList<ListNode> lists) { // write code here ListNode dummyNode = new ListNode(-1001); ListNode pHead1, pHead2; pHead1 = dummyNode; for(int i=0;i<lists.size();i++){ pHead2 = lists.get(i); pHead1 = Merge(pHead1, pHead2); } return dummyNode.next; } }
在合并两个的基础上,循环k次即可;
注意ArrayList类型的索引方法是list.get(i), 获取大小的方法是list.size()