Wins the Offer-16. Merging two sorted lists (C ++ / Java)

topic:

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.

analysis:

May be a new node, compare two values ​​come monotonically increasing list of the current node, next, if the current value is smaller than p1 p2, then the new node = p1, p1 to the next node, the new node also p to move to the next node.

Of course you can do with recursion. C ++ standard practice, Java recursive.

program:

C++

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1 == nullptr)
            return pHead2;
        if(pHead2 == nullptr)
            return pHead1;
        ListNode resHead(0);
        ListNode* p = &resHead;
        while(pHead1 && pHead2){
            if(pHead1->val < pHead2->val){
                p->next = pHead1;
                pHead1 = pHead1->next;
            }
            else{
                p->next = pHead2;
                pHead2 = pHead2->next;
            }
            p = p->next;
        }
        if(pHead1)
            p->next = pHead1;
        if(pHead2)
            p->next = pHead2;
        return resHead.next;
    }
};

Java

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        if(list1.val < list2.val){
            list1.next = Merge(list1.next, list2);
            return list1;
        }
        else{
            list2.next = Merge(list1, list2.next);
            return list2;
        }
    }
}

Guess you like

Origin www.cnblogs.com/silentteller/p/11886551.html