Get the App
SLTechnology News&Howtos  ›  Development  › 

How C++ merges K sorted linked lists

Shulou Source: shulou.com Published: 2022-06-02 03:31:51 09月18日 Update

The knowledge of this article "C++ how to merge K sorted lists" is not understood by most people, so the editor summarizes the following, detailed contents and clear steps, which can be used for reference. I hope you can get something after reading this article, let's take a look at this "C++ how to merge K sorted linked lists" article bar.

Merge k sorted linked lists and return the merged sorted linked list. Please analyze and describe the complexity of the algorithm.

Example:

Input: [1-> 4-> 5, 1-> 3-> 4, 2-> 6] output: 1-> 1-> 2-> 3-> 4-> 4-> 5-> Definition for singly-linked list.# class ListNode (object): # def _ init__ (self, x): # self.val = x # self.next = Noneclass Solution (object): def mergeKLists (self Lists): ": type lists: List [ListNode]: rtype: ListNode" # synthesize a large listlist and sort lists = [x for x in lists if x] if not lists or all ([not x for x in lists]): return head = lists.pop () curr = head while curr.next: Curr = curr.next while lists: tmp = lists.pop () curr.next = tmp while tmp.next: tmp = tmp.next curr = tmp if not head or not head.next: return head return self.mergeSort (head) def mergeSort (self Head): if not head.next: return head pre, slow, fast = None, head, head while fast and fast.next: prev, slow, fast = slow, slow.next, fast.next.next prev.next = None left = self.mergeSort (head) right = self.mergeSort (slow) return self.merge (left, right) def merge (self, left Right): if not left: return right if not right: return left if left.val < right.val: res = left res.next = self.merge (left.next, right) else: res = right res.next = self.merge (left Right.next) return res above is the content of this article on "how C++ merges K sorted linked lists" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Tags: Sorting content clocking articles knowledge articles complexity value complexity most that is more steps knowledge points examples algorithms industry information information channels channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi NVidia Apple Microsoft