本此的主題主要違歸併排序的應用Merge k Sorted Lists並且透過鏈表實現,首先我們先設置各個節點的模塊:
Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
實現歸併排序也不同的方法,這次使用遞歸的特性實現,創建mergeList(vector<ListNode*> list)的歸併排序主函數:
ListNode* mergeList(vector<ListNode*> &list)
{
ListNode *result;
if(list.empty())
return NULL;
while(list.size() > 1)
{
result = merge(result, list[0]);
list.erase(list.begin());
}
}
由於我們要實現k個鏈表的排序,所以利用vector存儲多個鏈表並將結果存放在result內,在循環中有調用merge函數下面會簡略講解,按照vector中的順序一一透過merge做歸併,再將排頭做移除。
merge函數的作用是將兩段鏈表合併,可以看到分別有四種情況,透過比較鏈表中元素的大小,再次調用merge的函數,在參數中必須更改為l1->next或l2->next式情況而定。
ListNode *merge(ListNode* l1, ListNode *l2)
{
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
if(l1->val <= l2->val){
l1->next = merge(l1->next, l2);
return l1;
}
else{
l2->next = merge(l1, l2->next);
return l2;
}
}