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

合并两个排序的链表

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

//问题出在哪呢?出在结构体的默认复制函数是浅拷贝,需要new一个初始化的节点才有用
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
#include <sys/types.h>
class Solution {
  public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        ListNode* newList = new ListNode(0);
        ListNode* nHead;
        nHead = newList;
        while (pHead1 != NULL && pHead2 != NULL)
        {
            if (pHead1->val<pHead2->val)
            {
                newList->next = pHead1;
                pHead1 = pHead1->next;
                cout << "路过1";
            }
            else {
                newList->next = pHead2;
                pHead2 = pHead2->next;
                cout << "路过2";
            }
            newList = newList->next;
        }
        while (pHead1)
        {
            newList->next = pHead1;
            newList = newList->next;
            pHead1 = pHead1->next;
            cout << "路过3";
        }
        while (pHead2)
        {
            newList->next = pHead2;
            newList = newList->next;
            pHead2 = pHead2->next;
            cout << "路过4";
        }
        return nHead->next;
    }
};

全部评论

相关推荐

这不纯纯作弊了吗😢😢😢
编程界菜鸡:信这个的这辈子有了,这智商你靠啥都没用
你找工作的时候用AI吗?
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
今天 13:05
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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