本文为剑指 offer 系列第十八篇。
主要知识点是链表,仍然是在遍历链表的基础上进行相关操作,非常经典。
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
找两个指针分别指向两个有序链表的头结点,然后依次找最小值放到存放结果的链表之中即可。
要记得考虑一个链表遍历完而另一个链表没有遍历完的情况。
解题代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| /* 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 && !phead2) return NULL; if(!phead1) return phead2; if(!phead2) return phead1; ListNode *head = NULL, *tail = NULL; ListNode *p1= phead1,*p2 = phead2; while(p1 && p2){ if(p1->val <= p2->val){ ListNode* temp = new ListNode(p1->val); if(!head){ head = temp; tail = temp; } tail->next = temp; tail = tail->next; p1= p1->next; }else{ ListNode* temp = new ListNode(p2->val); if(!head){ head = temp; tail = temp; } tail->next = temp; tail = tail->next; p2= p2->next; } } if(!p1 && !p2) return head; while(p1){ ListNode* temp = new ListNode(p1->val); if(!head){ head = temp; tail = temp; } tail->next = temp; tail = tail->next; p1= p1->next; } while(p2){ ListNode* temp = new ListNode(p2->val); if(!head){ head = temp; tail = temp; } tail->next = temp; tail = tail->next; p2= p2->next; } return head; } };
|
时间复杂度为O(n),空间复杂度为O(n)
以上,本题结束!