2つのインクリメンタルチェーンテーブルの合成

4043 ワード

2つの単調に増加したチェーンテーブルを入力し、2つのチェーンテーブルの合成後のチェーンテーブルを出力します.もちろん、合成後のチェーンテーブルは単調で減少しない規則を満たす必要があります.
非再帰方法:考え方:1.pHead 1とpHead 2は空ではなく、そのうちの1つが空であれば別のものに戻る.2.2つのチェーンテーブルが空でない場合、新しいチェーンテーブルヘッダノードansと一時的なノードpを作成し、pは最新に追加されたノードを表し、まずヘッダノードを比較し、小さいのは新しいチェーンテーブルのヘッダノードとなる.3.pHead 1とpHead 2を比較し続け、pのnextは小さいものを指し、小さいチェーンテーブルは後ろに移動し、同時にpも後ろに移動する.4.一方の合成が完了してNULLとなった場合、他方のチェーンテーブルはpの後に直接加算される.手順は次のとおりです.
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *ans,*p;
        ans=p=NULL;
        if(pHead1==NULL)return pHead2;
        if(pHead2==NULL)return pHead1;
        while(pHead1!=NULL&&pHead2!=NULL)
        {
            if(pHead1->val <= pHead2->val)
            {
                if(ans==NULL){
                    p=ans=pHead1;
                }else{
                    p->next=pHead1;
                    p=p->next;
                }                
                pHead1=pHead1->next;
            }
            else
            {
                if(ans==NULL)
                {
                    p=ans=pHead2;
                }else
                {
                    p->next=pHead2;
                    p=p->next;
                }

                pHead2=pHead2->next;
            }
        }
        if(pHead1==NULL)p->next=pHead2;
        if(pHead2==NULL)p->next=pHead1;
        return ans;
    }
};

再帰メソッドはMergeが出るたびに現在のノードのnextであることをよく考えなければならない.
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *ans=NULL;

        if(pHead1==NULL)return pHead2;
        if(pHead2==NULL)return pHead1;
        if(pHead1->val <= pHead2->val)
        {
           ans=pHead1;
           ans->next=Merge(pHead1->next,pHead2);
        }
        else 
        {
           ans=pHead2;
           ans->next=Merge(pHead1,pHead2->next);
        }
        return ans;
    }
};