Common algorithm questions: merge two-way single-chain tables and merge two-way Single-Chain Algorithms

Source: Internet
Author: User

Common algorithm questions: merge two-way single-chain tables and merge two-way Single-Chain Algorithms

Question: There are two incremental single-chain table L1 and L2. design an algorithm to merge all nodes of L1 and L2 into the incremental single-chain table L3. Requirement: the space complexity is O (1 ).

Train of Thought: This question can adopt a two-way merge idea, but the question requires the space complexity to be O (1), so the node cannot be copied, and it can only break L1 and L2 to insert the node into L3.

Code:

Void Merge (LinkList & L1, LinkList & L2, LinkList & L3) {LinkList * p = L1.head-> next, * q = L2.head-> next; LinkList * p1, * q1, * r; L1.head-> next = NULL; // set L1 and L2 to an empty table L2.head-> next = NULL; r = L3.head; while (p! = NULL & q! = NULL) // when neither of the tables is completely traversed {if (p-> data <q-> data) {p1 = p-> next; // Insert the node in L1 into L3 r-> next = p; r = p; p = p1;} else {q1 = q-> next; // Insert the node in L2 into L3 r-> next = q; r = q; q = q1 ;}} while (p! = NULL) // If L1 is not completely traversed, insert all the remaining nodes to L3 {p1 = p-> next; r-> next = p; r = p; p = p1;} while (q! = NULL) // If L2 is not completely traversed, insert all the remaining nodes to L3 {q1 = q-> next; r-> next = q; r = q; q = q1;} r-> next = NULL; // set the end node of L3 to NULL}

This algorithm does not contain new nodes, so the space complexity is O (1 ).

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.