问题描述
我需要编写一个双向链接列表,该列表可以与键盘输入或用户提供的数据文件一起使用。除此之外,我还需要在链接列表,插入的列表和插入的列表中预先插入(在正在浏览的视频中)。
这是无法修改的双向链表节点数据结构:
struct mynode {
int const value; // once initialized,cannot be updated
struct mynode *next;
struct mynode *prev;
};
Арrе-рrераreddаtаfilееxаmрlе已被列出:
30
20
50
70
10
0
鉴于文件,您应建立5个链接列表。链接列表中不应该包含0到0的第一个数据。鉴于大约5天内,未链接的列表应如下所示: 30 20 50 70 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;
}
一旦您填写了缺少的代码并且可以正常工作,就可以执行下一步。
-
从文件中读取数据(而不是硬编码值)
-
添加一个
print_list_sorted
函数。