从预制文件中创建链接列表

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

我正在尝试从c ++中的预制文件制作一个链表。我正在努力从文件中获取信息并使用该信息来创建列表的概念。这是到目前为止,我还需要具有从列表中任何位置插入和删除节点的功能。

struct node
{
    string name;
    int id;
    float gpa;
    node *next;
};
struct node* head;
void insertNodes(short id)
{
    struct node* new_node = (struct node*) malloc(sizeof(struct node));
    new_node->id = id;
    new_node->next = head;
    head = new_node;
}
void deleteNode() {
    if (head == NULL){
        cout << "List is empty" << endl;
        return;
    }
    cout << head->id << " is removed." << endl;
    head = head ->next;
}
int main() {
    head = NULL;
    node entry;
    fstream datafile;

    datafile.open("datafile.dat", ios::in | ios::binary);
    if (!datafile)
    {
        cout << "Error!!\n";
        return 0;
    }
    datafile.read(reinterpret_cast<char *>(&entry), sizeof(entry)); 
}
c++ oop data-structures linked-list singly-linked-list
1个回答
0
投票

如果您使用C ++进行此操作,则不应在结构的每个实例之前使用malloc和struct关键字。您可能应该创建自己的类来表示列表,并使用成员函数代替全局变量head

另外,您的插入函数似乎只接受输入值并将其添加到列表的末尾;通常,在列表中,除非您要调用方法“ pushback”或类似方法,否则您将需要插入点和值。

[此外,除非您重写以创建自己的List类,否则您当前尚未完成任何面向对象的编程,因为您只是按程序进行操作,而有关此代码的唯一c ++就是使用iostream和[ C0]。

建议您也将节点设为类。它主要是语义的,但是会让您养成习惯,即使您不想成为访问器,也可以给节点构造函数。

除了您在没有尝试任何内容的情况下索要信息,而且您的问题太过广泛。

© www.soinside.com 2019 - 2024. All rights reserved.