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

leetcode之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

程式碼:

#include<iostream>
#include<vector>

using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

ListNode* mergeTwoLists(ListNode* l1, ListNode*l2) {
	ListNode* head = new ListNode(0);
	ListNode* current = head;

	while (l1&&l2) {
		if (l1->val < l2->val) {
			current->next = l1;
			l1 = l1->next;
		}
		else {
			current->next = l2;
			l2 = l2->next;
		}

		current = current->next;
	}

	if (l1)current->next = l1;
	if (l2)current->next = l2;

	return head->next;
}

ListNode* mergeKLists(vector<ListNode*> &lists) {

	if (lists.size() <= 0)return NULL;
	ListNode* result = lists[0];

	for (int i = 1; i < lists.size(); i++) {
		result = mergeTwoLists(result, lists[i]);
	}

	return result;
}

int main() {
	ListNode* l1 = new ListNode(1);
	ListNode* l2 = new ListNode(4);
	ListNode* l3 = new ListNode(5);

	l1->next = l2;
	l2->next = l3;

	ListNode* l4 = new ListNode(1);
	ListNode* l5 = new ListNode(3);
	ListNode* l6 = new ListNode(4);
	
	l4->next = l5;
	l5->next = l6;

	ListNode* l7 = new ListNode(2);
	ListNode* l8 = new ListNode(6);

	l7->next = l8;

	vector<ListNode*> v;

	v.push_back(l1);
	v.push_back(l4);
	v.push_back(l7);

	ListNode* res=mergeKLists(v);

	while (res) {
		cout << res->val << " ";
		res = res->next;
	}

	
	return 0;
}

注意:

考慮vector為空的情況