Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- ListNode mergeTwoLists(ListNode list1, ListNode list2) {
- ListNode dummy = new ListNode();
- ListNode cur = dummy;
- while (list1 != null && list2 != null) {
- if (list1.val > list2.val) {
- cur.next = list2;
- cur = list2;
- list2 = list2.next;
- } else {
- cur.next = list1;
- cur = list1;
- list1 = list1.next;
- }
- }
- while (list1 != null) {
- cur.next = list1;
- cur = list1;
- list1 = list1.next;
- }
- while (list2 != null) {
- cur.next = list2;
- cur = list2;
- list2 = list2.next;
- }
- return dummy.next;
- }
- public ListNode mergeKLists(ListNode[] lists) {
- if (lists.length == 0) {
- return null;
- }
- int loopCount = 1;
- while (loopCount < lists.length) {
- for (int i = 0; i + loopCount < lists.length; i += loopCount*2) {
- lists[i] = mergeTwoLists(lists[i], lists[i + loopCount]);
- }
- loopCount *= 2;
- }
- return lists[0];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement