Topic:
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.
Idea 1: let two pointers point to two linked lists, who are small to insert the end of the current node into a new linked list
Code:
/*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==null) { return pHead2; } else if (PHead2==NULL ) { return pHead1; } //Two Hands ListNode *newhead=NULL; listnode *cur=null; listnode *p1=phead1; listnode *p2=phead2; listnode *temp=null; //Note that if this is the following: There is a big loophole //looks like Newhead's next is cur //. But when the second number is found, cur points to the other //newhead. There is only one node in the linked list /*while (p1!=null&&p2!=null) {if (p1->_data<=p2->_data) {cur=p1;p1= P1->_next;} Else{cur=p2;p2=p2->_next;} if (newhead==null) {newhead=cur;} Cur->_next=null;cur=cur->_next;} */ while (p1!=null&&p2!=null) { if (P1->val<=p2->val) { temp=p1; p1=p1->next; } else { temp=p2; p2=p2->next; } if ( Newhead==null) { newhead=temp; cur=newhead; } else { cur->next=temp; cur=cur->next; } } if (p1!=null) { cur->next=p1; } else { cur->next=p2; } return newhead; }};
idea two: by recursion, find the smallest element each time, add to the back of the new list
Code:
Listnode* merge (listnode* phead1, listnode* phead2) { //termination Condition if (PHead1==NULL) { return pHead2; } else if (phead2==null) { return pHead1; } ListNode *newhead=NULL; if (Phead1->val<=phead2->val) { newhead =pHead1; &Nbsp; newhead ->next=merge (phead1->next,phead2); } else { newhead =phead2; newhead ->next= Merge (Phead1,phead2->next); } return newhead; }
This article from "Momo is spicy moe" blog, please be sure to keep this source http://momo462.blog.51cto.com/10138434/1812767
Sword Point of Offer question 17: Merge two sorted lists