C 链表定义如何重新实现列表
嗨,这可能是一个愚蠢的问题,需要一个简单的解决方案,但我只是在互联网上找不到答案。
所以我正在为考试做练习并做作业。该程序的工作是找出链表中心的值是什么(如果列表的长度是奇数)
structdef 是:
typedef struct IntList IntList;
struct IntList {
int value;
IntList* next;
};
而我现在的确切问题是,当我尝试使用:
list = list->next;
我想在循环中逐步转到链表第 n 个位置(中心)的愿望列表。
有人知道我必须如何重写这个吗?如果您需要更多信息来帮助,请直接说出来,我会解释更多。
使用该函数,我检查列表的长度,在其他函数中,我有一个循环,仅到达长度的中间。
int length_list(IntList* list) {
int n = 0;
for(IntList* node = list; node != NULL; node = node->next) n++;
return n;
}
Hi this is probably a stupid question to ask with a simple solution but I just can't find an answer in the internet.
So I was exercising for an exam and worked on an assignment. The program has the job to find out what the value in the center of a linked list is (if the length of the list is an odd number)
The structdef is:
typedef struct IntList IntList;
struct IntList {
int value;
IntList* next;
};
and my exact problem right now is that I get a segmentation fault when I try using:
list = list->next;
I want to go step by step in a loop to go to the wished list at the nth position (the center) of the linked list.
Someone knows how I have to rewrite this? If you need more Information to help just say so and I will explain more.
With that function I check the length of the list and in my other function I have a loop which only goes to the mid of the length.
int length_list(IntList* list) {
int n = 0;
for(IntList* node = list; node != NULL; node = node->next) n++;
return n;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
循环结束后
for(IntList* node = list; node != NULL; node = node->next) n++;
你肯定有node==NULL
。< br>这并不是立即的问题。
但根据您对返回的
n
值的处理方式,您可能会遇到相差一的问题。例如,在只有一个条目的列表中(毕竟 1 是奇数),尝试使用 1 太高的值可能会导致尝试访问不存在的节点。因此,我怀疑您的问题可以通过将循环更改为来解决
for(IntList* node = list; node->next != NULL; node = node->next) n++;
,这样它就在最后一个现有节点上结束,而不是在后面。返回值会更低,无论你做什么都会“更加小心”。或者尝试与您显示并询问的小代码片段类似的操作,
list = list->next;
仅当next
不为 NULL 时才执行此操作,而不是 if只有list
不为 NULL。After this loop ends
for(IntList* node = list; node != NULL; node = node->next) n++;
you surely havenode==NULL
.That is not immediatly a problem.
But depending on what you do with the value of
n
which you return you might have an off-by-one problem. E.g. in a list with exactly one entry (1 is odd after all), the attempt to use a value which is 1 too high could result in an attempt to access a non-existing node.Because of this I suspect that your problem might be solved by changing the loop to
for(IntList* node = list; node->next != NULL; node = node->next) n++;
, so that it ends on the last existing node, instead of behind. The return value will be lower, whatever you do with it will be "more-careful".That or try something similar with the small code fragment you show and ask about,
list = list->next;
only do that if thenext
is not NULL, not if onlylist
is not NULL.