题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:
也在考虑能不能更优雅的代码写法,但是最后,还是两边都写一下,能增加代码清晰度。
代码:
/*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 *ret, *cur; if (pHead1->val < pHead2->val) { ret = cur = pHead1; pHead1 = pHead1->next; } else { ret = cur = pHead2; pHead2 = pHead2->next; } while (pHead1 && pHead2) { if (pHead1->val < pHead2->val) { cur->next = pHead1; cur = pHead1; pHead1 = pHead1->next; } else { cur->next = pHead2; cur = pHead2; pHead2 = pHead2->next; } } if (pHead1){ cur->next = pHead1; } if (pHead2) { cur->next = pHead2; } return ret; }};
结果:
通过您的代码已保存答案正确:恭喜!您提交的程序通过了所有的测试用例