欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[剑提供--C/C++] JZ25 合并两个排序链表-代码

最编程 2024-07-07 11:18:39
...
/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstddef>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead1 ListNode类 
     * @param pHead2 ListNode类 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        // write code here
       //如果一方为空,则直接返回另一方
        if(pHead1==NULL){
            return pHead2;
        }
        if(pHead2==NULL){
            return pHead1;
        }

         ListNode * pHead3=NULL;
         ListNode * newHead;
         //pHead3==NULL是最初的时候
        while(pHead1 && pHead2){
            if(pHead1->val < pHead2->val){
                if(pHead3==NULL){
                    pHead3=pHead1;
                    newHead=pHead3;
                }else {
                    pHead3->next=pHead1;
                    pHead3=pHead3->next;
                }
                pHead1=pHead1->next;
            }else {
               if(pHead3==NULL){
                    pHead3=pHead2;
                    newHead=pHead3;
                }else {
                    pHead3->next=pHead2;
                    pHead3=pHead3->next;
                }
                pHead2=pHead2->next;
            }
            
        }
        //如果比较完之后某一队还有剩余,则直接将剩余的部分插到队尾
        if(pHead1){
            pHead3->next=pHead1;
        }
        if(pHead2){
            pHead3->next=pHead2;
        }
        return newHead;
    }
};