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. The idea is to merge the idea of the algorithm, note that the first to determine the two linked list nodes are not empty, judge the size while loop, to see which list node is not empty, using sentinel node Method processing head node.
/*struct ListNode {int val; struct ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};*/classSolution { Public: ListNode* Merge (listnode* pHead1, listnode*pHead2) { if(PHead1 = = nullptr) && (pHead2 = =nullptr)) { returnnullptr; } if(PHead1 = =nullptr) { returnpHead2; } if(PHead2 = =nullptr) { returnPHead1; } ListNode* Dummyhead =NewListNode (-1); ListNode* head =Dummyhead; while(PHead1! = nullptr && pHead2! =nullptr) { if(PHead1, Val < pHead2,val) {HeadNext =PHead1; PHead1= PHead1Next; } Else{HeadNext =pHead2; PHead2= PHead2Next; } head= HeadNext; } if(PHead1! =nullptr) {HeadNext =PHead1; } if(PHead2! =nullptr) {HeadNext =pHead2; } returnDummyheadNext; }};
15 merging two sorted lists