[LeetCode] Merge k Sorted Lists
2012-11-18 10:35
316 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
类似于Merge Sort的方法做k-1次
类似于Merge Sort的方法做k-1次
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *merge(ListNode *node1, ListNode *node2) { if (node1 == NULL) return node2; if (node2 == NULL) return node1; ListNode *head = NULL; ListNode *curNode = NULL; ListNode *p = node1; ListNode *q = node2; while(p && q) { ListNode *node; if (p->val < q->val) { node = p; p = p->next; } else { node = q; q = q->next; } if (head == NULL) { head = curNode = node; } else { curNode->next = node; node->next = NULL; curNode = node; } } if (p) { curNode->next = p; } else if (q) { curNode->next = q; } return head; } ListNode *mergeKLists(vector<ListNode *> &lists) { // Start typing your C/C++ solution below // DO NOT write int main() function if (lists.size() == 0) return NULL; ListNode *head = lists[0]; for(int i = 1; i < lists.size(); i++) head = merge(head, lists[i]); return head; } };
相关文章推荐
- [LeetCode]23. Merge k Sorted Lists
- LeetCode 21 - Merge Two Sorted Lists
- 【leetcode】【单链表】【61】Merge k Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- Leetcode-Merge Two Sorted Lists
- Leetcode---21. Merge Two Sorted Lists
- LeetCode Merge k Sorted Lists
- 【LeetCode】23. Merge k Sorted Lists
- LeetCode::Merge Two Sorted Lists
- LeetCode 学习 LinkedList 专项(4)—— Merge Two Sorted Lists
- leetcode 23:Merge k Sorted Lists(15-10-10)
- 【LeetCode】【Linked List】Merge Two Sorted Lists
- Leetcode题解-23. Merge k Sorted Lists
- LeetCode题解:Merge k Sorted Lists
- Merge Two Sorted Lists--LeetCode
- [LeetCode]Merge Two Sorted Lists
- [leetcode]21. Merge Two Sorted Lists(java)
- [Leetcode] Merge Two Sorted Lists
- LeetCode: Merge k Sorted Lists
- leetcode: Merge k Sorted Lists