Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How C++ merges ordered linked lists

Shulou Source: shulou.com Published: 2022-05-31 14:28:33 10月02日 Update

This article mainly explains "how C++ merges ordered linked lists". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "how C++ merges ordered linked lists".

Algorithm:

The core of the algorithm lies in the merging operation of two ordered linked lists. The merging of K ordered linked lists is only a deformation problem, which is first split into two ordered lists of k bank, and then the proportional sequence is reduced to 1 sequence.

Topic 1: merge two ordered linked lists

Code implementation:

/ / algorithm: recursive algorithm, l1=l2, offset l2.Next, and then recursive l2.Next and L1 operations. / * Definition for singly-linked list. * type ListNode struct {* Val int * Next * ListNode *} * / func mergeTwoLists (L1 * ListNode, L2 * ListNode) * ListNode {if L1 = = nil {return L2} if L2 = = nil {return L1} if l1.Val < l2.Val {l1.Next = mergeTwoLists (l1.Next, L2) return L1} l2.Next = mergeTwoLists

Topic 2: merge k sorted lists

Code implementation:

/ * solution 2: divide-and-conquer + recursion; divide-and-conquer: two groups, decreasing in turn, k _ r _ p _ r _ x _ r _ x _ r _ r * type ListNode struct {* Val int * Next * ListNode *} * / func mergeKLists (lists [] * ListNode) * ListNode {if len (lists) = = 0 {return nil} if len (lists) = = 1 {return lists [0]} for {n: = len (lists) / 2 ok: = len (lists)% 2 = = 1 for iRank Ok {lists = lists [: n]} else {lists [n] = lists [len (lists)-1] lists = lists [: len 1]} if len (lists) = 1 {break} return lists [0]}

Func mergeLists (L1 * ListNode, L2 * ListNode) * ListNode {if L1 = = nil {return L2} if L2 = = nil {return L1} if l1.Val < l2.Val {l1.Next = mergeLists (l1.Next, L2) return L1}

L2.Next = mergeLists (L1, l2.Next) return L2} Thank you for reading, this is the content of "how C++ merges ordered linked lists". After the study of this article, I believe you have a deeper understanding of how C++ merges ordered linked lists, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Ordering centering two algorithms recursion topics learning code content sorting proportional series number just just ideas situations series articles more core Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft Docker macOS OPPO Reno