The title describes the input of two monotonically increasing lists, the output of the list of two linked lists, of course, we need to synthesize the linked list to meet monotonic rules. Idea: Non-recursive
Class Solution {public: listnode* Merge (listnode* pHead1, listnode* pHead2) { if (!phead1) return pHead2; if (!phead2) return pHead1; listnode* Head; listnode* p; //take smaller values as head node if (phead1->val<=phead2->val) { &NBSP ; HEAD=PHEAD1; phead1=phead1->next; } else{ head=phead2; phead2=phead2->next; } //Start traversal merge P=head; //p work pointer for the merged linked list while (phead1&&phead2) { //when there is a list to the end, the loop ends if (phead1->v Al<=phead2->val) { //If the node of the linked list 1 is less than the node of the linked List 2 p->next=phead1; //take this node join list &N Bsp phead1=phead1->next; //list 1 move back one p=p->next; //work pointer move back one &NBS P } else{ & nbsp //otherwise take the list 2 node &NBS P p->next=phead2; &NBSp phead2=phead2->next; p=p->next; } } if (pHead1 = = NULL) //list 1 traversed &N Bsp P->next = pHead2; //If List 2 is also traversed, then phead2=null if (pHead2 = = NULL) //List 2 traversed P->next = PHead1; ///If List 1 is also completed, then Phead1=null return Head; };
Idea: recursive algorithm.
/*struct listnode {int val;struct listnode *next; ListNode (int x): Val (x), Next (NULL) {}};*/class Solution {public: listnode* Merge (listnode* pHead1, listnode* pHead2 ) { if (!phead1) return pHead2; if (!phead2) return pHead1; if (phead1->val <= phead2->val) { phead1->next= Merge (phead1->next,phead2); return pHead1; } else { Phead2->next = Merge (phead1,phead2->next); return pHead2;}} ;
https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337
Merge two sorted lists