LeetCode Merge k Sorted Lists

本文提供了一种解决LeetCode上合并K个已排序链表问题的方法,通过遍历比较的方式逐步合并多个链表。文章包含了完整的C++实现代码,并展示了如何创建示例链表及调用函数进行合并。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// LeetCode_MergekSortedLists.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

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

ListNode *mergeKLists(vector<ListNode *> &lists) {
	int lenlist = lists.size();
	if (lenlist==0)
	return NULL;
	
	ListNode **parr = new ListNode *[lenlist];
	for (int i=0;i<lenlist;i++)
	{
		parr[i] = lists[i];
	}
	ListNode *head=NULL;
	bool flag=true;
	ListNode *p=NULL,*pmin;
	ListNode *s=NULL;
	while(flag)
	{
		int i=0,kmin=0;
		pmin = parr[i];//search for the first non-null element point
		while(pmin==NULL)
		{
			i++;
			if (i==lenlist)
			{
				flag=false;
				break;
			}
			pmin = parr[i];
			kmin = i;
		}
		if (flag==false)
		{
			continue;
		}
		for (int j=0;j<lenlist;j++)//search for the least value point
		{
			if (parr[j]!=NULL&&parr[j]->val<pmin->val)
			{
				pmin = parr[j];
				kmin = j;
			}
		}
		//s = pmin;
		if(parr[kmin]!=NULL)
			parr[kmin] = parr[kmin]->next;
		if (head==NULL)
		{
			head = pmin;//head = s;
			p = head;
		}
		else
		{
			if(p!=NULL)
			{
				p->next = pmin;//p->next = s;
				p = p->next;
			}
		}
	}
	if(p!=NULL)
		p->next = NULL;
	delete[] parr;
	return head;
}

int _tmain(int argc, _TCHAR* argv[])
{
	ListNode *la1 = new ListNode(1);
	ListNode *la2 = new ListNode(4);
	ListNode *la3 = new ListNode(7);
	ListNode *lb1 = new ListNode(2);
	ListNode *lb2 = new ListNode(5);
	ListNode *lb3 = new ListNode(8);
	ListNode *lc1 = new ListNode(3);
	ListNode *lc2 = new ListNode(6);
	ListNode *lc3 = new ListNode(9);
	la1->next = la2;
	la2->next = la3;
	lb1->next = lb2;
	lb2->next = lb3;
	lc1->next = lc2;
	lc2->next = lc3;
	ListNode *head=NULL;
	vector<ListNode*> vec;
	vec.push_back(la1);
	vec.push_back(lb1);
	vec.push_back(lc1);
	head = mergeKLists(vec);
	ListNode *p=head;
	while(p)
	{
		cout<<p->val<<" ";
		p=p->next;
	}
	system("pause");
	return 0;
}
网上看别人用什么大根堆,有这必要吗?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值