[Data Structure and Algorithm] Merging of two ordered linked lists

Title Description
Input two monotonically increasing linked lists, and output the combined list of the two linked lists. Of course, we need the combined list to satisfy the monotonic non-decreasing rule.

/*
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;
        ListNode* p2=pHead2;
        ListNode* newhead=NULL;
        ListNode * node=NULL;
        if(p1->val<=p2->val){
            newhead=p1;
            node=p1;
            p1=p1->next;           
        }
        else{
            newhead=p2;
            node=p2;
            p2=p2->next;            
        }
        while(p1!=NULL && p2!=NULL){
            if(p1->val <= p2->val){
               
                node->next=p1;
                node=p1;   
                p1=p1->next;
               
            }
            else{              
                node->next=p2;
                node=p2;               
                p2=p2->next;
            }
        }
        
        if(p1==NULL){
            node->next=p2;
        }
        else if (p2==NULL){
            node->next=p1;
        }
        return newhead;
            
    }
};
Published 19 original articles · Likes0 · Visits 383

Guess you like

Origin blog.csdn.net/qinchun/article/details/105524638