Title Description:
Input two monotonically increasing list, output two list of linked lists, of course, we need to synthesize the linked list to meet the monotone non-reduction rules.
Algorithm idea:
The idea of this topic is to refer to two linked lists by two pointers, recursively comparing the worth of two lists, and assigning them to new head nodes. Until the end. It is important to note that we need to check whether the list of two incoming lists is empty;
Algorithm implementation:
1#include <iostream>2#include <stdlib.h>3 using namespacestd;4 5typedefstructlistnode{6 intdata;7 structListNode *Next;8 }listnode;9 TenListNode * Merge (ListNode *phead1, ListNode *pHead2) {One if (pHead1 = = null) {//check whether the null return phead2;13}14 if (pHead2 = = null) {15 Return phead1;16} - -ListNode *phead =NULL; + - if(Phead1->data < phead2->data) {//recursive merging of two linked lists +Phead =PHead1; APhead->next = Merge (phead1->Next, pHead2); at } - Else{ -Phead =pHead2; -Phead->next = Merge (PHead1, phead2->next); - } - in returnPhead; - } to +ListNode *createlist (intx) {//Create a linked list - Longnum; theListNode *phead =NULL; *ListNode *p =NULL; $ Panax Notoginseng while(x-->0){ -Cin>>num; thelistnode* pnew =NewListNode (); + if(Pnew = =NULL) { A exit (exit_failure); the } +Pnew->data =num; -Pnew->next =NULL; $ $ if(Phead = =NULL) - { -Phead =pnew; thep =Phead; - } Wuyi Else the { -P->next =pnew; Wup = p->Next; - } About } $ returnPhead; - } - - intMain () { A intm, N; + theListNode *P1 =NULL; -ListNode *P2 =NULL; $ListNode *result =NULL; the the while(cin>>m>>N) { theP1 =createlist (m); theP2 =createlist (n); -result =Merge (P1, p2); in the if(Result = =NULL) { thecout<<"NULL"<<Endl; About } the Else{ theListNode *index =result; the while(Index! =NULL) { +cout<<index->data<<' '; -index = index->Next; the }Bayicout<<Endl; the } the } -}
Reference data:
"The sword means offer"
Merge two sorted lists