【问题标题】:Adding Elements to doubly-linked lists将元素添加到双向链表
【发布时间】:2017-02-25 23:01:47
【问题描述】:

我正在尝试使用 while 循环将元素添加到双向链表。正在制作节点,但它们都存储相同的单词,这是我正在阅读的文件的最后一个单词。这是我的while循环:

while(fscanf(text, "%s", word) == 1)
{
    struct node *temp;
    temp = new_node(word); //Creates a new node
    temp->prev = cursor; //Cursor represents current position in linked list
    temp->next = NULL;
    cursor->next = temp;
    cursor = temp;
}

光标在while循环开始之前被初始化到列表的头部。

这是我的节点结构:

struct node
{
    struct node* prev;
    struct word_entry* data;
    struct node* next;
};

我的 while 循环有什么问题?为什么它会不断覆盖以前的节点?请,谢谢!

【问题讨论】:

  • 错误可能在new_node() 中,您没有向我们展示。
  • temp = new_node(word); --> temp = new_node(strdup(word));

标签: c struct doubly-linked-list


【解决方案1】:

您的文件位于text 中,并且您正在将单词加载到一个名为word 的字符数组中。

由于您的循环将所有节点分配给同一个数组,temp = new_node(word); 所有节点都指向同一个字符数组。

当你将文件中的最后一个单词读入word时,由于所有节点都指向它,所以它们都读出了同一个单词。

您必须为每个节点分配单独的单词存储,并在分配给节点时将单词复制到该存储:

nodeword = malloc(strlen(word) + 1);
if(nodeword) {
  strcpy(nodeword, word);
  nodeword[strlen(word)] = 0;
  temp = new_node(nodeword);
}
else {
  break;
}

如果你愿意,也可以使用 strdup()..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多