Title Description
Two monotonically increasing input list and output list after synthesis of two lists, of course, after that we need to meet synthesis list - decreasing the rules.
Problem-solving ideas
Basic Operation inspection list, difficult to grasp that the input data, the input data must consider the comprehensive
1. When a single linked list is NULL;
2. The two lists are NULL;
3. A list traversal is completed, the remaining nodes as well as other chain
4. The two lists of equal length;
The following C ++ code realization are given specifically:
/* 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; } if(pHead2==NULL){ return pHead1; } ListNode *p1=pHead1,*p2=pHead2,*nHead=NULL; ListNode = Q * NULL; // determining first node fused IF (P1-> Val <= P2-> Val) { Q = P1; P1 = P1-> Next; } the else { Q = P2; P2 = P2- > Next; } NHEAD = Q; // set two pointers pointing to two lists, one by one to take a new list element is connected to the while (P1 = P2 = NULL &&!! {NULL) IF (P1-> Val <= P2 -> Val) { Q -> Next = P1; P1 = P1-> Next; q=q->next; }else{ q->next=p2; p2=p2->next; q=q->next; } } if(p1==NULL){ q->next=p2; }else{ q->next=p1; } return nHead; } };