LeetCode -- Merge k Sorted Lists

Source: Internet
Author: User

LeetCode -- Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 

Question: Merge k ordered linked lists and return an ordered linked list.

Idea: I have previously done the merge of two ordered linked lists, so I want to simplify the merge of k linked lists into the merge of two linked lists.

 

public ListNode mergeKLists(List
 
   lists){if(lists == null)return null;return mergeLists(lists,0,lists.size()-1);}public ListNode mergeLists(List
  
    lists,int start,int end) {if(start > end)return null;if(start==end)return lists.get(start);if(start+1 == end)return mergeTwoLists(lists.get(start),lists.get(end));int mid = (start+end)/2;return mergeTwoLists(mergeLists(lists,start,mid),mergeLists(lists,mid+1,end));}public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode p1 = l1, p2 = l2, dummy = new ListNode(-1), p = dummy;while (p1 != null && p2 != null) {if (p1.val <= p2.val) {p.next = p1;p1 = p1.next;} else {p.next = p2;p2 = p2.next;}p = p.next;}if (p1 != null)p.next = p1;if (p2 != null)p.next = p2;return dummy.next;}// Definition for singly-linked list.public class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}
  
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.