题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1 == NULL && pHead2 == NULL)
            return NULL;
        if(pHead1 == NULL){
            return pHead2;
        }
        if(pHead2 == NULL){
            return pHead1;
        }
        ListNode *Head = NULL;
        ListNode *p = NULL;
        
        while(pHead1 && pHead2){
            if(pHead1->val <= pHead2->val){
                if(Head == NULL){
                    Head = p = pHead1;
                }else{
                     p->next = pHead1;
                     p = p->next;
                }
                pHead1 = pHead1->next;
            }
            //这里必须是else,因为第一步当中指针操作之后可能也满足第二个if,所以两个if不行
            else if(pHead1->val > pHead2->val){
                if(Head == NULL){
                    Head = p = pHead2;
                }else{
                     p->next = pHead2;
                     p = p->next;
                }
                pHead2 = pHead2->next;
                
            }
        }
            if(pHead1 == NULL){
                p->next = pHead2;
            }
            if(pHead2 == NULL){
                p->next = pHead1;
            }
        return Head;
    }
};

  记录一下踩的坑。注释处必须是else,如果俩if就报错

posted @ 2019-03-15 15:24  路在脚下丶  阅读(677)  评论(0编辑  收藏  举报