题目来源:牛客网
编程链接
题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解析:
用递归的思路。
代码:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1 == nullptr)
return pHead2;
if(pHead2 == nullptr)
return pHead1;
return (pHead1->val > pHead2->val)?(pHead2->next = Merge(pHead1,pHead2->next),pHead2 ):
(pHead1->next = Merge(pHead1->next,pHead2),pHead1);
}
};
运行时间:3ms;占用内存:356k
代码解析:先比较大小,确定谁小,谁就是头结点,头结点的下一个结点继续通过merge的方式获得。
,表示先进行合并,之后返回头结点。
又写了一遍:
/*
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==nullptr)return pHead2;
if (pHead2==nullptr)return pHead1;
return (pHead1->val > pHead2->val)?(pHead2->next = Merge(pHead1,pHead2->next),pHead2):\
(pHead1->next = Merge(pHead1->next,pHead2),pHead1);
}
};