当前位置: 技术问答>linux和unix
看看您的c语言基础如何?链表问题
来源: 互联网 发布时间:2017-01-02
本文导语: #include #include #include #include #include #include #include struct wd_path { char *absolute_path; struct wd_path *next; }; static struct wd_path *insert_path(struct wd_path *n_path, char *path) { struct wd_path *s_path, *p_path, ...
#include
#include
#include
#include
#include
#include
#include
struct wd_path
{
char *absolute_path;
struct wd_path *next;
};
static struct wd_path *insert_path(struct wd_path *n_path, char *path)
{
struct wd_path *s_path, *p_path, *insert_path;
insert_path = (struct wd_path *)safe_malloc(sizeof(struct wd_path));
insert_path->absolute_path = path;
insert_path->next = NULL;
if (n_path == NULL)
{
//n_path = (struct wd_path *)safe_malloc(sizeof(struct wd_path));
n_path = insert_path;
return n_path;
}
s_path = n_path;
p_path = insert_path;
while (s_path->next != NULL)
{
s_path = s_path->next;
}
p_path->next = NULL;
s_path->next = p_path;
return n_path;
}
int main()
{
struct secbox_path *path_list = NULL;
path_list = insert_path(path_list, "111");
path_list = insert_path(path_list, "222");
path_list = insert_path(path_list, "333");
path_list = insert_path(path_list, "444");
for(;;)
{
while (path_list != NULL)
{
printf("%sn", path_list->absolute_path);
path_list = path_list->next;
}
}
}
以上是我在一本书上看到的一个关于创建链表的题目,说这段代码有问题, 我专门把这段代码在电脑上测试了一下,结果输入信息如下:
444
444
444
444
题目的本意是要求输出:
111
222
333
444
这样的信息,要求指出问题的原因所在,并做修改。 我分析了几个小时了,没有找出原因来。群里的那个c语言的基础比较好,能指出问题的原因所在吗?
|
你写错了函数吧,int main()
{ struct secbox_path *path_list = NULL; //此处写错了,struct wd_path *path_list = NULL
path_list = insert_path(path_list, "111");
path_list = insert_path(path_list, "222");
path_list = insert_path(path_list, "333");
path_list = insert_path(path_list, "444");
for(;;) { while (path_list != NULL)
{ printf("%sn", path_list->absolute_path);
path_list = path_list->next; } } }
然后就可以运行了。结果也对。
{ struct secbox_path *path_list = NULL; //此处写错了,struct wd_path *path_list = NULL
path_list = insert_path(path_list, "111");
path_list = insert_path(path_list, "222");
path_list = insert_path(path_list, "333");
path_list = insert_path(path_list, "444");
for(;;) { while (path_list != NULL)
{ printf("%sn", path_list->absolute_path);
path_list = path_list->next; } } }
然后就可以运行了。结果也对。