时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 热度指数:691701
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
实现代码1:(带头节点的实现方式)
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
//带头节点的实现方法
ListNode *NewHead=new ListNode(0);//struct中已定义构造函数
//NewHead->next=NULL;
ListNode *Node=NewHead;
while(pHead1!=NULL&&pHead2!=NULL)
{
if(pHead1->val<pHead2->val)
{
Node->next=pHead1;
Node=pHead1;
pHead1=pHead1->next;
}
else
{
Node->next=pHead2;
Node=pHead2;
pHead2=pHead2->next;
}
}
if(pHead1==NULL)
{
Node->next=pHead2;
}
else
{
Node->next=pHead1;
}
return NewHead->next;//不能返回头结点,应该返回第一个有效值的节点指针即头指针
}
};
实现代码2:(不带头节点的实现方式)
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode *NewHead=NULL;
ListNode *Node=NewHead;
while(pHead1!=NULL&&pHead2!=NULL)
{
if(pHead1->val<pHead2->val)
{
if(NewHead==NULL)NewHead=pHead1;//需要单独处理头指针
else Node->next=pHead1;
Node=pHead1;
pHead1=pHead1->next;
}
else
{
if(NewHead==NULL)NewHead=pHead2;
else
{
Node->next=pHead2;
}
Node=pHead2;
pHead2=pHead2->next;
}
}
if(pHead1==NULL)
{
if(NewHead==NULL)NewHead=pHead2;
else
{
Node->next=pHead2;
}
}
else
{
if(NewHead==NULL)NewHead=pHead1;
else
{
Node->next=pHead1;
}
}
return NewHead;
}
};
结论:即使参数指针或返后值要求为第一个有效数据结点的指针(即头指针而不是头结点),但是使用头结点可以统一很多操作,只需最后返后头结点的next结点即可,还是比不带头结点的链表处理简洁的多。

本文介绍了一种将两个单调递增链表合并成一个保持单调不减规则链表的算法。提供了两种实现方式:一种是使用带头节点的方法,另一种是不使用头节点。前者通过创建一个虚拟头节点简化了合并过程,后者直接操作链表的有效节点。

被折叠的 条评论
为什么被折叠?



