连接两个排序的单链表
牛客中的代码是这样的:
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL && pHead2 == NULL)
{
return NULL;
}
if (pHead1 == NULL || pHead2 == NULL)
{
return pHead1 == NULL ? pHead2 : pHead1;
}
ListNode* ppHead1 = pHead1;
ListNode* ppHead2 = pHead2;
ListNode* newHead = new ListNode(0);
ListNode* cur = newHead;
while (ppHead1 && ppHead2)
{
if (ppHead1->val < ppHead2->val)
{
cur->next = ppHead1;
ppHead1 = ppHead1->next;
}
else
{
cur->next = ppHead2;
ppHead2 = ppHead2->next;
}
cur = cur->next;
}
if (ppHead1 == NULL)
{
cur->next = ppHead2;
}
if (ppHead2 == NULL)
{
cur->next = ppHead1;
}
return newHead->next;
}
vs中的代码是这样的:
#pragma once
#include<assert.h>
#include<iostream>
using namespace std;
typedef int DataType;
//结构体 链表
typedef struct ListNode
{
DataType data;
struct ListNode *next;
}ListNode;
//初始化链表
void InitList(ListNode** pHead)
{
*pHead = NULL;
}
//插入节点//尾插法
void Insert(ListNode*& pHead, DataType x)
{
if (pHead == NULL)
{
pHead = new ListNode[sizeof(ListNode)];
pHead->data = x;
pHead->next = NULL;
}
else
{
ListNode* tial = pHead;
ListNode* pos = new ListNode[sizeof(ListNode)];
while (tial->next != NULL)
{
tial = tial->next;
}
pos->data = x;
tial->next = pos;
pos->next = NULL;
}
}
//遍历单链表
void PrintList(ListNode* pHead)
{
ListNode* cur = pHead;
assert(pHead);
while (cur)
{
cout << cur->data << "->";
cur = cur->next;
}
cout << "NULL" << endl;
}
//翻转单链表
ListNode* Revers(ListNode* pHead)
{
ListNode* newhead = NULL;
ListNode* cur = pHead;
while (cur)
{
ListNode* tmp = cur;
cur = cur->next;
tmp->next = newhead;
newhead = tmp;
}
return newhead;
}
//合并两个单链表
ListNode* Merge(ListNode*& pHead1, ListNode*& pHead2)
{
if (pHead1 == NULL && pHead2 == NULL)
{
return NULL;
}
if (pHead1 == NULL || pHead2 == NULL)
{
return pHead1 == NULL ? pHead2 : pHead1;
}
ListNode* ppHead1 = pHead1;
ListNode* ppHead2 = pHead2;
ListNode* newHead = new ListNode[sizeof(ListNode)];
ListNode* cur = newHead;
while (ppHead1 && ppHead2)
{
if (ppHead1->data < ppHead2->data)
{
cur->next = ppHead1;
ppHead1 = ppHead1->next;
}
else
{
cur->next = ppHead2;
ppHead2 = ppHead2->next;
}
cur = cur->next;
}
if (ppHead1 == NULL)
{
cur->next = ppHead2;
}
if (ppHead2 == NULL)
{
cur->next = ppHead1;
}
return newHead->next;
}
两个唯一的不同是在那个新链表的表头,重新申请的空间,牛客中的初始化一定要看结构体中是如何说的,很明显,按牛客给出的结构体中,对于节点的初始化时需要显式调用构造函数,而vS中的是人为初始化,这就是,用这种方法,牛客编译不通过的唯一原因