[LeetCode] 32.Linked List - Merge Two Sorted Lists merge two ordered lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Because there is no space requirements, it is conceivable ListNode * head = new ListNode (INT_MIN); redefine a linked list, each linked list size compare two host node then added to the definition of a new list.

Finally, note that the release of the first node space.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode*p1=l1;
        ListNode*p2=l2;
        if(p1==NULL) return p2;
        if(p2==NULL) return p1;
        ListNode*head = new ListNode(INT_MIN);
        ListNode*tag=head;
        while(p1!=NULL&&p2!=NULL)
        {
            if(p1->val>=p2->val)
            {
                ListNode*D=p2;
                p2=p2->next;
                D->next=NULL;
                tag->next=D;
                tag=tag->next;
            }
            else{
                ListNode*D=p1;
                p1=p1->next;
                D->next=NULL;
                tag->next=D;
                tag=tag->next;
            }
        }
        if(p1!=NULL)
        {
            tag->next=p1;
            ListNode*H=head;
            head=head->next;
            delete H;
        }
        if(p2!=NULL)
        {
            tag->next=p2;
            ListNode*H=head;
            head=head->next;
            delete H;
        }
        return head;
    }
};

 

Guess you like

Origin www.cnblogs.com/hu-19941213/p/11462897.html