标签:solution else input opened ide pre ret lse 非递归
{1,2,3,4,5,6}
1.非递归:
申请新的空间用于存放合并后的链表;
若当前pHead1的val值不大于pHead2的val值,则将pHead1放入新链表中,并将pHead1后移一位;
若当前pHead2的val值不大于pHead1的val值,则将pHead2放入新链表中,并将pHead2后移一位;
若某一指针为空,且另一指针非空,则将非空指针加入新链表
这样的时间复杂度为O(n+m),空间复杂度为O(1)
/* 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 && pHead2==nullptr) return NULL; ListNode* p = new ListNode(0); ListNode* ans = p; while(pHead1 && pHead2) { if(pHead1->val <= pHead2->val) { p->next = pHead1; pHead1 = pHead1->next; p = p->next; } else { p->next = pHead2; pHead2 = pHead2->next; p = p->next; } } p->next = pHead1?pHead1:pHead2; return ans->next; } };
2.递归
没啥好说的,代码简单明了.时间复杂度为O(n+m),同时因为递归会调用栈的缘故空间复杂度为O(n+m)
/* 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; else if(pHead2==NULL) return pHead1; ListNode* p = new ListNode(0); if(pHead1->val <= pHead2->val) { p = pHead1; p->next = Merge(pHead1->next, pHead2); } else { p = pHead2; p->next = Merge(pHead1, pHead2->next); } return p; } };
没啥好说的,代码简洁
标签:solution else input opened ide pre ret lse 非递归
原文地址:https://www.cnblogs.com/alan-W/p/14238315.html