我一直在用Kochan的C 4版编程研究C。我试图在将头撞到墙上几个小时和寻求见解之间取得平衡。
我在有关指针的章节中,练习使您构建了许多功能,然后扩展到双向链表。一项是使列表点从前到后和从后到前。我的问题是,从前向后移动时,最后一个条目会在我要跳过该值的位置显示一个值。相同的方向。我一直在使用的方法是在节点的前面和后面都有一个节点条目,以便能够将条目添加到列表的开头和结尾。请注意,我们尚未达到内存分配之类。我也留在我的插入功能,以防万一那里有问题。提前致谢
#include <stdio.h>
#include <stdbool.h>
struct entry
{
struct entry *previous;
int value;
struct entry *next;
};
void insertEntry(struct entry *what, struct entry *where)
{
what->next = where->next;
what->previous = where->previous;
where->next = what;
where->previous = what;
}
void printEntries_Reverse (struct entry initial)
{
while (initial.previous != NULL){
printf("%i \n", initial.previous->value);
initial.previous = initial.previous->previous;
}
}
void printEntries(struct entry initial)
{
while (initial.next != NULL){
printf("%i \n", initial.next->value);
initial.next = initial.next->next;
}
printf("\n");
}
int main (void)
{
struct entry head, foot, n0, n1, n2, n3, n4, nx;
struct entry *list_ptr, *list_end;
list_ptr = &n0;
list_end = &n4;
n1.value = 100;
n2.value = 200;
n3.value = 300;
n4.value = 400;
n0.next = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = NULL;
n0.previous = NULL;
n1.previous = &n0;
n2.previous = &n1;
n3.previous = &n2;
n4.previous = &n3;
nx.value = 250;
insertEntry(&nx, &n2);
printEntries(*list_ptr);
printEntries_Reverse(*list_end);
return 0;
}```
一个问题是该printEntries
函数实际上正在中断列表。
这行:initial.next = initial.next->next;
在列表中的每个节点中重新分配下一个指针。
我更改了打印条目功能,使其看起来像这样:
void printEntries(struct entry *initial)
{
while (initial != NULL){
printf("%i \n", initial->value);
initial = initial->next;
}
printf("\n");
}
主要原因是要遍历列表而不更改列表节点中实际存在的任何指针。它仅更改指针变量initial
,而不更改列表的内容。
我知道那种把头撞在墙上的感觉。我曾经gdb
在这里找到错误,并且强烈建议向学习C的任何人学习基础知识。
Gdb非常令人恐惧,但是95%的时间中,您需要使用的只是本文中“ Misc”部分中的部分https://beej.us/guide/bggdb/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句