struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
// write code here
if (listsLen == 0)
{
return NULL;
}
if (listsLen == 1)
{
return *(lists);
}
//根据题目使用了类似于哈希的算法?。数据的取值范围为|val| = 1000,那么也就是说大小为-1000~1000,一共2001个数字。
int aiNode[2001];
//记得初始化,否则可能会有随机值
memset(aiNode,0,sizeof(aiNode));struct ListNode *pstTemp2 = NULL;
int i = 0;
//获取第一个节点,以下循环,防止出现连续多个链表为空的情况
while(NULL == pstTemp2){
pstTemp2 = lists[i++];
if(i == listsLen)
{
break;
}
}
//循环置0.
i = 0;while(i < listsLen)
{
while(NULL != pstTemp2)
{
//哈希表,+1000是为了计算负值。
aiNode[pstTemp2->val + 1000]++;
//链表节点后移
if(NULL != pstTemp2->next){
pstTemp2 = pstTemp2->next;
}
//当前节点的后一个节点为空时,接上下一个链表。
else if((1+i) < listsLen){
while(NULL == pstTemp2->next)
{
//接上下一个链表。
pstTemp2->next = lists[++i];
//防止访问下一链表时越界。
if(i >= listsLen){
break;
}
}
//接上之后,链表节点后移
pstTemp2 = pstTemp2->next;}
else
{
//没有下一个链表了,计数+1,跳出当前循环。
i++;break;
}
}
}
i = 0;
pstTemp2 = NULL;
while(NULL == pstTemp2)
{
pstTemp2 = lists[i++];
if(i == listsLen)
{
break;
}
}
//接下来的循环就是对链表中的所有节点进行赋值了。
while(i < 2001){
while(0 < aiNode[i])
{
aiNode[i] --;
if(NULL != pstTemp2)
{
pstTemp2->val = i - 1000;
pstTemp2 = pstTemp2->next;
}
else
{
break;
}
}
i++;
}
return *lists;
}