将节点添加到单个链接列表

时间:2013-03-03 04:11:20

标签: c++ linked-list

我正在编写反汇编程序并使用链表来保存符号文件(sym_file)中的数据。我一直在看所有其他帖子,但仍然无法让它工作! (继续得到分段错误)我试图在列表的末尾附加节点,以便我可以跟踪head_node。

void read_symbol_file(char* file_name)
{
    struct node* head_node = new struct node;
    struct node* node = new struct node;
    struct node* temp;
    ifstream sym_file(file_name, ios::out);
    char label[16];
    char the_type[6];
    char address[6];

    if(sym_file.is_open())
    {
        while (!sym_file.eof())
        {
            sym_file >> label;
            sym_file >> the_type;
            sym_file >> address;

            if(strcmp(the_type, "line") == 0)
            {
                node->type = line;
                node->label = label;
                node->address = atoi(address);
            }
            else if(strcmp(the_type, "block") == 0)
            {
                node->type = block;
                node->label = label;
                node->address = atoi(address);
            }
            else if(strcmp(the_type, "ascii") == 0)
            {
                node->type = ascii;
                node->label = label;
                node->address = atoi(address);
            }
            else if(strcmp(the_type, "word") == 0)
            {
                node->type = word;
                node->label = label;
                node->address = atoi(address);
            }
            else
            {
                cout << "invalid label" << endl;
                exit(0);
            }

            if(head_node == NULL)
            { 
                head_node = node;
                head_node->next = node;
            }
            else
            {
                temp = head;
                while(temp->next != NULL)
                    temp = temp->next;
                temp->next = NULL;
            }
        }
        sym_file.close();
    }

    else
    {
        cout << "File does not exist or could not be found." << endl;
        exit(0);
    }
    cout << head_node->label << endl;

}

1 个答案:

答案 0 :(得分:1)

这一行应该是编译器错误:

          temp = head;

因为没有变量'head'的声明

第二个问题是“新节点”的分配在循环之外,所以你只有一个“节点”不断被覆盖。该行应该在'while'循环内移动:

   struct node* node = new struct node;

第三,else块永远不会将指向'node'的指针指向下一个变量。应该是

  temp->next = node;

此代码中还存在与head_node相关的其他几个问题,一旦分配,它们将不会是== NULL。关于将结构的地址分配给指针和将一个结构的内容复制到另一个结构之间的区别似乎有些混淆,如* head_node = * node;

在这种情况下,不需要使用'new'来分配head_node。这只是一个指针,可以初始化为NULL。