很简单
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/class Solution {public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {ListNode *head = new ListNode;ListNode *p1 = list1, *p2 = list2, *p = head;if (p1 == nullptr && p2 == nullptr) return nullptr;if (p1 == nullptr && p2 != nullptr) return p2;if (p1 != nullptr && p2 == nullptr) return p1;while (true) {if (p1->val <= p2->val) {p->next = p1;p1 = p1->next;} else {p->next = p2;p2 = p2->next;}p = p->next;if (p1 == nullptr) {p->next = p2;break;}if (p2 == nullptr) {p->next = p1;break;}}return head->next;}};
执行结果:
通过
显示详情
添加备注
执行用时:4 ms, 在所有 C++ 提交中击败了92.63% 的用户
内存消耗:14.5 MB, 在所有 C++ 提交中击败了18.85% 的用户
通过测试用例:208 / 208
