The content of this blog post is related to a single-chain table. For reprinting, please indicate the record. Otherwise, you must
1. merge two ordered Single-Chain tables into an ordered single-chain table
The methods are divided into Recursive Implementation and non-Recursive Implementation. Both methods do not open up memory space.
The data structure of the linked list is reversed in the single-chain table of this blog, such as Joseph ring.
Recursive Implementation:
// Recursively merge two ordered single-chain table linknode * merge_list (linknode * phead1, linknode * phead2) {If (phead1 = NULL) return phead2; If (phead2 = NULL) return phead1; If (phead1 = NULL & phead2 = NULL) return NULL; linknode * pmergedhead = NULL; If (phead1-> value <phead2-> value) {response = phead1; pmergedhead-> next = merge_list (phead1-> next, phead2);} else {pmergedhead = phead2; pmergedhead-> next = merge_list (phead1, phead2-> next);} return pmergedhead ;}
Non-Recursive Implementation:
// Non-recursive merge two ordered Single-Chain tables (no extra space) linknode * non_merge_list (linknode * phead1, linknode * phead2) {If (phead1 = NULL) return phead2; if (phead2 = NULL) return phead1; If (phead1 = NULL & phead2 = NULL) return NULL; linknode * pmergedhead = NULL; linknode * q = NULL; if (phead1-> value <phead2-> value) {pmergedhead = phead1; phead1 = phead1-> next;} else {Signature = phead2; phead2 = phead2-> next ;} Q = pmergedhead; while (phead1 & phead2) {If (phead1-> value <phead2-> value) {q-> next = phead1; phead1 = phead1-> next ;} else {q-> next = phead2; phead2 = phead2-> next;} q = Q-> next;} If (phead1) {While (phead1) {q-> next = phead1; q = Q-> next; phead1 = phead1-> next ;}} if (phead2) {While (phead2) {q-> next = phead2; q = Q-> next; phead2 = phead2-> next ;}} return pmergedhead ;}
2. output intermediate elements in a single-chain table (if the number of linked list nodes is an even number, either of the two intermediate nodes is output)
Idea: Use two pointers to traverse from the first node. One step is taken, and the other two steps are taken. When a pointer taking two steps goes to the end of the linked list, at this time, the pointer taking one step points to the intermediate node of the linked list.
The Code is as follows:
LinkNode* print_mid_node(LinkNode *pHead){LinkNode *pOne = pHead, *pTwo = pHead;while(1){pOne = pOne->next;pTwo = pTwo->next->next;if(pTwo==NULL || pTwo->next==NULL)return pOne;}}
3. Determine whether a single love table has a ring
The idea is the same as that of the second question, but the ending condition is different. If a pointer taking one step equals a pointer taking two steps at a time, it indicates that the linked list has a ring
The Code is as follows:
bool is_circle_list(LinkNode *pHead){LinkNode *pOne = pHead, *pTwo = pHead;while(1){pOne = pOne->next;pTwo = pTwo->next->next;if(pOne == pTwo)return true;if(pTwo==NULL || pTwo->next==NULL)return false;}}