链表合并

题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题:本题可有循环也可由递归实现,代码给出了递归实现的方式。
代码:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{

if (pHead1 == NULL) return pHead2;
if (pHead2 == NULL) return pHead1;
ListNode *mergeList = NULL;
if (pHead1->val < pHead2->val) {
    mergeList = pHead1;
    mergeList->next = Merge(pHead1->next, pHead2);
}
else {
    mergeList = pHead2;
    mergeList->next = Merge(pHead1, pHead2->next);
}
return mergeList;

}
};

猜你喜欢

转载自blog.csdn.net/double_s_c/article/details/76166111