c - 将新节点链接到 c 中的链接列表的问题

标签 c linked-list

我是 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/

相关文章:

将常规 C 风格编码文件转换为 GNU 风格编码标准

c - 如何删除两个索引之间的链表节点?

c++ - 写入多个文件描述符

c - 数组程序的输出

c - 如何处理来自getopt的字符

java - 如何根据两个对象参数对对象链接列表进行排序?

c - 在 C 中读取行并将行分隔到链表中

调用带参数的 perl 例程

java - 在已排序的链表中插入节点

java - 如何在 JTable 中显示双向链表数据?