将结构添加到c中的双向链表中

问题描述 投票:1回答:1

我是编程新手(第一学期),在这里找到的例子在做作业时总是给我很大帮助!现在,我必须做一个更大的项目,并且我已经读了很多东西,但是我只是无法解决问题。

我需要做什么

  1. 从文件中的文本读取数据
  2. [通过strtok()将其排序为结构(通过将从文件读取的数据分配给结构字段,将其放入结构中)
  3. 将结构添加到双向链接列表

问题

  1. 当我打印列表时,列表中只有第一个和最后一个结构,中间的结构消失了(第一个条目“ head”与pNode=head;一起定义在主体中]
  2. 如果我尝试以向前的顺序打印列表,它将无限打印最后一个列表元素。

我已尝试仅复制我认为对该问题重要的部分。由于我已经做了很多尝试,甚至不知道在哪里查找错误,因此不胜感激。提前非常感谢!

void read_file(struct node *pNode, FILE *fp) {
    struct node *head = pNode;
    head->next=NULL;
    head->prev=NULL;

    /*(fread, strtok_r, strtok,...)*/

    while (token1 != NULL) {
        //allocating memory for the structs
        struct node*new = calloc(1, sizeof(struct node));
        *new =*pNode;

        while (token2 != NULL) {
            new->index = (*token2 - 48);
            token2 = strtok(NULL, "\n"); //jump to next token (=next line)

            new->name = malloc(sizeof(char)*strlen(new->name)+1);
            strcpy(new->name, token2);
            token2 = strtok(NULL, "\n");

            /*(some more sorting into struct)*/

            /*ADD STRUCT TO LIST*/

            if (head->next==NULL){
                head->next=new;
                head->prev=NULL;
                new->prev=head;
                new->next=NULL;
            }

            new->next = head->next;
            head->next = new;
            new->next->prev = new;
            new->prev = head;
            head->prev = NULL;

            pNode=new;
        }

        token_recipe = strtok_r(NULL, "#", &temp); //jump to next token (=next recipe)
    }

    printf("\nLinked list in backwards order:\n");

    while (pNode != NULL) {
        printf("%s ", pNode->name);
        pNode= pNode->prev;
    }
    puts("\n");
}
c struct doubly-linked-list
1个回答
0
投票

您在这里遇到了混乱的纠结,我将尽力帮助解决。

        if (head->next==NULL){
            head->next=new;
            head->prev=NULL;
            new->prev=head;
            new->next=NULL;
        }

        new->next = head->next;
        head->next = new;
        new->next->prev = new;
        new->prev = head;
        head->prev = NULL;

您第一次有headnewhead->nextNULL,因此您需要执行if块中的位并最终显示如下列表:

head new

然后将new->next指向head->next ...这意味着您将new->next指向new

head new-> new

[new->next->prev = new因此new->prev现在也等于new

head-> new new

但是您将其修复后将其指向head,并将head->prev设置为NULL,因为您从未更改过它,所以它可能已经存在。

head new-> new

而且您仍然得到new的循环循环,将其指向下一个节点。

完全废弃该代码。 pNode是列表中的上一个节点,最初与head相同-这是您应该链接到的变量。]​​>

new->prev = pNode;
pNode->next = new;

未指定的上一个和下一个值应该已经设置为NULL(因为您正在使用calloc)或指向内存中的有效位置,因此您无需弄乱它们。] >

然后在循环末尾正确执行以下操作

pNode = new;

将列表的末尾指向创建的最新节点。

您还应该摆脱下一行,因为new是一个新的新节点-在pNode中不应复制任何内容,因此,您需要设置下一个和上一个值不需要,因为它们已经正确设置为NULL

*new =*pNode;
© www.soinside.com 2019 - 2024. All rights reserved.