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

合并两个排序的链表

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;
    }
};

全部评论

相关推荐

我是小红是我:学校换成中南
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务