力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
首先我们实现一个合并两个有序链表的操作,然后使用归并的思想对数组中的链表进行排序。
- /**
- * 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*a,ListNode*b)
- {
- if((a==nullptr)||(b==nullptr)) return a?a:b;
-
- ListNode* head=new ListNode(0);
- ListNode* tail=head;
- while(a!=nullptr&&b!=nullptr)
- {
- if(a->val<=b->val)
- {
- tail->next=a;
- a=a->next;
- }
- else
- {
- tail->next=b;
- b=b->next;
- }
- tail=tail->next;
- }
- tail->next=(a?a:b);
- return head->next;
- }
- // 归并操作
- ListNode* merge(vector
&lists,int l,int r) - {
- if(l==r) return lists[l];
- if(l>r) return nullptr;
- int mid=(l+r)/2;
- return mergeTwoLists(merge(lists,l,mid),merge(lists,mid+1,r));
- }
- ListNode* mergeKLists(vector
& lists) - {
- return merge(lists,0,lists.size()-1);
- }
- };