题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//方法一:非递归
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
//创建一个结点为0的链表
ListNode* current = new ListNode(0);
ListNode* result= current;
//开始遍历两个链表,将较小当前较小值的结点添加进current链表中
while (pHead1 != NULL && pHead2 != NULL)
{
if (pHead1->val <= pHead2->val) {
current->next = pHead1;
current = current->next;
pHead1 = pHead1->next;
}
else
{
current->next= pHead2;
current = current->next;
pHead2 = pHead2->next;
}
}
//那个链表没遍历完,直接添加未遍历完的链表
if (pHead1 != NULL) {
current->next = pHead1;
}
if (pHead2 != NULL) {
current->next = pHead2;
}
//返回合并后的链表
return result->next;
}
};
/*
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) {
return pHead2;
}
if (pHead2 == NULL) {
return pHead1;
}
ListNode * result = NULL;
if (pHead1->val <= pHead2->val) {
result = pHead1;
result->next = Merge(pHead1->next,pHead2);
}
else
{
result = pHead2;
result->next = Merge(pHead1, pHead2->next);
}
return result;
}
};
网友评论