题解 | 合并两个排序的链表

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
//https://blog.nowcoder.net/n/61e747ffe3a44931967b79fe11c7d936(哨兵节点以及递归方法)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead1 ListNode类 
     * @param pHead2 ListNode类 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        // write code here
        if(pHead1==nullptr){
            return pHead2;
        }
        if(pHead2==nullptr){
            return pHead1;
        }
        
        ListNode *result = pHead2->val>pHead1->val?pHead1:pHead2, *head=result;
        ListNode *pot1=pHead1, *pot2=pHead2;
        if(result==pHead1){
            pot1=pHead1->next;
        }
        else{
            pot2=pHead2->next;
        }

        while(pot1!=nullptr||pot2!=nullptr){
            if(pot1==nullptr){
                head->next = pot2;
                return result;
            }
            if(pot2==nullptr){
                head->next = pot1;
                return result;
            }
            if(pot1->val<=pot2->val){
                head->next = pot1;
                head = head->next;
                pot1 = pot1->next;
                continue;
            }
            else{
                head->next = pot2;
                head = head->next;
                pot2 = pot2->next;
                continue;
            }
        }
        return result;
    }
};

全部评论

相关推荐

在看牛客的社畜很积极:身高体重那一行信息去掉,学校那一行的信息放上面,找半天都没找到你是哪个学校什么专业的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务