1. 程式人生 > >[leetcode] Merge k Sorted Lists

[leetcode] Merge k Sorted Lists

Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

Solution: 這題可以參考歸併排序演算法的合併過程。採用的是分治的思想。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) { if (listsSize == 0) return NULL; if (listsSize == 1) return *lists; struct ListNode *pNode1=mergeKLists(lists, listsSize/2); struct ListNode *pNode2=mergeKLists(lists+listsSize/2, listsSize-listsSize/2); struct ListNode *
pNewListRoot,*pNewList; if (pNode1 && pNode2 && pNode1->val > pNode2->val) { pNewList = pNode2; pNode2 = pNode2->next; } else if (pNode1) { pNewList = pNode1; pNode1 = pNode1->next; } else if (pNode2) { pNewList = pNode2;
pNode2 = pNode2->next; } else { return NULL; } pNewListRoot = pNewList; while (pNode1 || pNode2) { if (pNode1 == NULL) { pNewList->next = pNode2; pNode2 = pNode2->next; pNewList = pNewList->next; continue; } if (pNode2 == NULL) { pNewList->next = pNode1; pNode1 = pNode1->next; pNewList = pNewList->next; continue; } if (pNode1->val > pNode2->val) { pNewList->next = pNode2; pNode2 = pNode2->next; } else { pNewList->next = pNode1; pNode1 = pNode1->next; } pNewList = pNewList->next; } return pNewListRoot; }