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

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead1 ListNode类 
     * @param pHead2 ListNode类 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        // write code here

        
        ListNode *head = nullptr;
        ListNode *head1 = nullptr;
        ListNode *head2 = nullptr;
        ListNode* curr = nullptr;

        //首先排除有空指针的现象
        if(!pHead1 || !pHead2)
        {
            if(!pHead1)
            {
                head = pHead2;
                
            }else {
                head = pHead1;
            }
            return head;
        }
       if(pHead1->val > pHead2->val)
       {
        head = pHead2;
        head1 = pHead1;
        head2 = pHead2->next;
        curr = head;

       }
       else {
       head = pHead1;
       head1 = pHead1->next;
       head2 = pHead2;
       curr = head;
       }

       //得到具体的头节点和当前的位置
       while(head1 || head2)
       {
        if(head1 == nullptr)//head1先耗尽
        {
            //直接连接当前head2的值
            curr->next = head2;
            break;
        }
        else if(head2 == nullptr)//head2 先耗尽
        {
            curr->next = head1;
            break;
        }
        else {  //head1 和 head2 都不为空
            if(head1->val > head2->val)
            {
                curr->next = head2;
                curr = head2;
                head2 = head2->next;
            }
            else {
                curr->next = head1;
                curr = head1;
                head1 = head1->next;
            }
        }
       }



        return head;
    }
};

全部评论

相关推荐

漂亮的海豚在炒股:把西电加粗
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务