LeetCode 23:合并K个排序链表(Merge k Sorted Lists)解法汇总

文章目录

  • My Solution

更多LeetCode题解

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

My Solution

建立一个名为res的list,对每个链表的每个节点,依次往res中插入。(这种方法没有利用到每个链表的有序特性,复杂度较高)

class Solution {
     
public:
	ListNode* mergeKLists(vector<ListNode*>& lists) {
     
		if (lists.size() == 0) return NULL;
		if (lists.size() == 1) return lists[0];
		ListNode* res = new ListNode(INT_MIN);
		for (size_t i = 0; i < lists.size(); i++) {
     
			ListNode* p = lists[i];
			while (p) {
     
				ListNode* q = p->next;
				insertNode(p, res);
				p = q;
			}
		}
		return res->next;
	}
	void insertNode(ListNode* node, ListNode* list) {
     
		ListNode* l = list;
		//insert into the first place
		if (l->val > node->val) {
     
			list = node;
			node->next = l;
			return;
		}
		//insert into a middle place
		ListNode* q = l->next;
		while (q) {
     
			if (q->val > node->val) {
     
				l->next = node;
				node->next = q;
				return;
			}
			l = l->next;
			q = q->next;
		}
		//insert into the last place
		if (l->val <= node->val) {
     
			l->next = node;
			node->next = NULL;
		}
		return;
	}
};

你可能感兴趣的:(LeetCode刷题题解记录,LeetCode,合并K个排序链表,Merge,k,Sorted,Lists)