之前PTA做过类似的题目,当时那道题应该是每次新建一个节点 ,这次利用的原本存在的节点构成了合并后的链表。
几点注意:1、空的头节点最后要删去,用delete删去
2、构造空的头节点时,要传递构造函数(constructor)要求的参数,一开始没有加参数,报错,加参数之后通过运行。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL && pHead2==NULL) return NULL;
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
ListNode *pHead, *pRear1, *pRear2, *pRear, *pTemp;
pRear1 = pHead1; pRear2 = pHead2;
pHead = new ListNode(0); pRear = pHead;
while((pRear1 != NULL)&&(pRear2 != NULL)){
if(pRear1->val <= pRear2->val){
pRear->next = pRear1;
pRear = pRear->next;
pRear1 = pRear1->next;
}
else{
pRear->next = pRear2;
pRear = pRear->next;
pRear2 = pRear2->next;
}
}
if(pRear1 == NULL){
pRear->next = pRear2;
}
else{
pRear->next = pRear1;
}
//回收空的头节点的内存
pTemp = pHead;
pHead = pHead->next;
delete pTemp;
return pHead;
}
};