gpt4 book ai didi

c++ - 实现数据存储在堆上的双向链表?

转载 作者:搜寻专家 更新时间:2023-10-31 02:11:20 24 4
gpt4 key购买 nike

我正在尝试实现一个双向链表,其中节点存储在堆栈中,但节点的数据存储在堆中。您可以使用 push() 将包含数据的新节点添加到列表中,并使用 pop() 删除最后一个元素。

我对 push() 方法有疑问。

#include <iostream>

using namespace std;

struct Data {
string name;
int age;
};

struct Node {
struct Node *next;
struct Node *previous;
struct Data *d;
};

struct Node *first;
struct Node *last;

void init() {
first = last = NULL;
}


void push(Data d) {
Node *temp;

if(first == NULL){
first = new Node();
first->d = malloc(sizeof(struct Data *));
first->next = NULL;
first->previous = NULL;
last = first;
} else if(last->next == NULL) {
last->next = new Node();
temp = last;
last = last->next;
last->previous = temp;
last->d = first->d = malloc(sizeof(struct Data *));
}
}


int main(int argc, char *argv[]) {
init();

Data d;

d.name = "Name1";
d.age = 19;
push(d);

d.name = "Name2";
d.age = 24;
push(d);

d.name = "Name3";
d.age = 25;
push(d);

d.name = "Name4";
d.age = 18;
push(d);

d.name = "Name6";
d.age = 20;
push(d);
}

我总是得到以下错误:

Untitled.cpp:29:12: error: assigning to 'struct Data *' from incompatible type 'void *'
first->d = malloc(sizeof(struct Data *));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Untitled.cpp:38:22: error: assigning to 'struct Data *' from incompatible type 'void *'
last->d = first->d = malloc(sizeof(struct Data *));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors generated.

为什么会出现以下错误?如何解决?我做错了什么?

最佳答案

建议:不要使用malloc,在C++中使用newdelete来处理堆。更强烈的建议:永远不要混合 new/deletemalloc/free。该错误来自于 C++ 需要从 void*

进行强制转换这一事实
first->d = (struct Data*)malloc(sizeof(struct Data *));
^ this is also wrong (read more later)

其他建议:了解smart pointers和可能的容器。它们会让您省去很多麻烦,同时让您专注于算法。

从算法上讲,你的(我想是不完整的)代码可能不会做你想做的事:你正在为一个指针分配空间(Node 对象已经有了),所以你最终会一个指针指向另一个指针(?)的空间。这可能是您最初的意思

first->d = new Data(d);

我将把其余部分作为练习离开。

关于c++ - 实现数据存储在堆上的双向链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43760810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com