我是 C 的新手,也是编程的新手,我刚刚开始研究链表。
static struct post {
char * str;
struct post * next;
}
head = {0, NULL};
int stringdb_add(const char * str) {
int pos = 0;
struct post * new_input = (struct post * ) malloc(sizeof(struct post));
new_input - > str = (char * ) malloc(strlen(str) + 1);
if (head.next == NULL) {
strcpy(new_input - > str, str);
new_input - > next = NULL;
head.next = new_input;
} else {
while (head.next - > next) {
++pos;
head.next = head.next - > next;
}
strcpy(new_input - > str, str);
new_input - > next = NULL;
head.next - > next = new_input;
}
return pos;
}
函数“stringdb_add”应该返回新节点放置的位置,但是当我测试函数时我只得到(00111111 ....)。
这可能是因为该列表从未正确链接。
最佳答案
while (head.next->next) { ++pos; head.next = head.next->next; }
您正在永久更改 head.next
这肯定不是您想要的。你可能想要这样的东西:
struct post *p = &head;
while (p->next->next)
/* ... */
挑剔:strcpy(new_input->str, str)
可以在一个地方,在 if
之前。
关于c - 将新节点链接到 c 中的链接列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21348838/