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 ).