[英]C - Doubly Linked List - Node's content is not correct (hard to explain)
我发现在标题中很难解释这一点,而没有实际显示代码和问题...所以就到这里了。 我遗漏了有效的方法,因此阅读起来并不多。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <ctype.h>
struct tnode {
struct tnode *prev;
char *word;
struct tnode *next;
};
struct tnode *talloc(void)
{
...
}
struct tnode *addlist(struct tnode *p, char *w)
{
...
}
void removelist(struct tnode *p, char *w)
{
while (1)
{
if (strcmp(p->word,w) == 0)
{
p->next->prev = p->prev;
p->prev->next = p->next;
goto out;
}
else if (strcmp(p->word,w) > 0)
{
p = p->prev;
}
else p = p->next;
}
out:;
return p;
}
void tprint(struct tnode *root)
{
...
}
main()
{
struct tnode *root;
root = talloc();
root->word = "doberman";
root->next = talloc();
root->prev = talloc();
//I am using a blank string at the beginning and end instead of leaving it NULL. When I tried leaving it NULL, I would get inaccessability errors.
root->next->word = "";
root->prev->word = "";
//I don't remember why I made "current" but it is working so I don't want to mess with it.
struct tnode *current;
current = talloc();
current = root;
current = addlist(root, "giraffe");
current = addlist(root, "gemini");
current = addlist(root, "apple");
current = addlist(root, "azure");
current = addlist(root, "rabbit");
current = addlist(root, "zambia");
current = addlist(root, "viking");
current = addlist(root, "cat");
current = addlist(root, "dog");
current = addlist(root, "tree");
current = addlist(root, "domino");
removelist(root, "azure");
tprint(root);
}
removelist方法当前从2-4个项目中而不是从1个项目中删除的数据超过了应该删除的数量,当我在调试器中逐步执行该方法时,我注意到“ p-> word”与“ p”不匹配。
例如,调试器将说“ p-> word”当前为“ doberman”,然后告诉我“ p”当前包含“ apple”。
我的问题是:这怎么可能? 如果“ p”是苹果节点,那么“ p-> word”如何成为杜宾犬? 它确实搞砸了该方法,因为它会认为在正确的位置进行删除,而实际上却并非如此。
比较时是否应该删除使用
if (strcmp(p->word,w) > 0)
当第一个不匹配的字符在ptr1中的值大于ptr2中的值时,它将返回true
我假设您要删除匹配的项目,所以这是一个问题,但不是问题。 在致电删除以确保添加所有项目之前,您是否尝试过打印出列表? 当您逐步执行goto语句时会发生什么?
你的第一个
if (strcmp(p->word,w) > 0)
应该
if (strcmp(p->word,w) == 0)
我认为您仍然必须将p-> next和p-> prev设置为NULL。 否则,仍然可以遍历p。 也许那给了您有趣的结果。
最后我怀疑这是打印方法的问题。 似乎我在这里提出的每个问题都以这种方式结束...答案与我在这里提出的问题无关,但所有答案仍将我引向解决方案。
无论如何,感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.