C中插入排序程序的双链表



我需要编写一个双链接端列表,该列表可以与键盘输入或用户提供的数据文件一起使用。除此之外,我还需要能够在列表中(在列表中(打印列表。

以下是无法修改的双链表节点数据结构:

struct mynode {
int const value; // once initialized, cannot be updated
struct mynode *next;
struct mynode *prev;
};

文件列表为

30

20

50

70

10

0

在文件的基础上,可以用5个数据建立一个链接列表。第0个标记是文件的第2个标记,第0个可以包含在链接列表中。在第五天,链接列表可能会出现以下情况:30<=>20<=>50<=>70<=>10

打印以下列表:70<=>50<=>30<=>20<=>10

我需要在3个源文件中编译它,并且只使用insertsort算法。有人能帮我做这个项目吗?我是C编程的新手。

以下是一些入门技巧。但我不会为你写所有的代码。

这一切都是关于将任务分解为一些小的简单子任务,您可以逐一解决这些任务。

从编写一些代码开始,这些代码可以从固定数字构建列表。

struct mynode {
int const value; // once initialized, cannot be updated
struct mynode *next;
struct mynode *prev;
};
struct mylist {
struct mynode *head;
struct mynode *tail;
};
void insert(struct mylist *list, int value)
{
struct mynode *n = malloc(sizeof *n);
if (n == NULL) exit(1);
*(int *)&n->value = value;  // Ugly trick to handle constness :-(
n->next = NULL;
n->prev = list->tail;    
if (list->tail == NULL)
{
// First node
list->head = n;
list->tail = n;
}
else
{
// Add to the tail
... this part I leave to you ...
}
}
void print_list_inorder(struct mynode *n)
{
while(n)
{
... add code to print value of n ...
n = n->next;
}
}
void free_list(struct mynode *n)
{
... add code to free all elements ...
}
int main(void)
{
struct mylist list = {NULL, NULL};
insert(&list, 30);
insert(&list, 20);
insert(&list, 50);
insert(&list, 70);
insert(&list, 10);
print_list_inorder(list.head);
free_list(list.head);
return 0;
}

一旦您填写了缺失的代码并开始工作,您就可以采取下一步行动。

  1. 从文件中读取数据(而不是硬编码值(

  2. 添加一个print_list_sorted函数。

最新更新