【发布时间】:2021-08-12 19:26:06
【问题描述】:
我最后在这里要完成的是对一个包含多个链表的结构数组进行排序,并返回 1 个合并列表并进行排序。
例子
Input: [1->4->5, 1->3->4, 2->6]
Output: 1->1->2->3->4->4->5->6
输入是数组,如示例中所示,其中有 3 个不同的列表排序错误。
输出是最终的排序列表。
我试图做的是尝试像普通结构数组一样访问数组,然后一次排序 2 个。
我的代码
#include <stddef.h>
#ifndef STRUCT_LISTNODE
#define STRUCT_LISTNODE
typedef struct s_listnode
{
int val;
struct s_listnode* next;
} listnode;
#endif
#ifndef STRUCT_LISTNODE_ARRAY
#define STRUCT_LISTNODE_ARRAY
typedef struct s_listnode_array
{
int size;
listnode **array;
} listnode_array;
#endif
listnode* sort(listnode* first, listnode* second){
listnode* newNode;
if(first == NULL && second == NULL)
return NULL;
if (first == NULL)
return second;
if (second == NULL)
return first;
// checking if the value on the first list bigger than the second or equal
if (first->val >= second->val) {\
// if yes that means that the second should be first.
newNode = second;
newNode->next = sort(first, second->next);
} else {
newNode = first;
newNode->next = sort(first->next, second);
}
return newNode;
}
listnode* merge_k_sorted_lists(listnode_array* head)
{
listnode *newNode;
for(int i = 0 ; i < head->size; i++){
newNode = sort(head->array[0], head->array[i]);
}
return newNode;
}
当我尝试运行我的代码时,我根本没有得到任何返回值。
【问题讨论】:
-
是时候学习如何使用 调试器 在监控变量及其值的同时逐语句执行代码。然后进入对
sort的递归调用。我还建议您在创建列表时同时使用笔和纸来“绘制”列表。在merge_k_sorted_lists函数中,所有这些都应该让您更容易看到newNode的变化以及它的变化。 -
你的函数
sort真的在做merge。 -
merge_k_sorted_lists中循环的第一次迭代将列表 0 用于sort的两个参数。
标签: arrays c sorting struct linked-list