gpt4 book ai didi

c++ - 链表/vector 中的指针

转载 作者:行者123 更新时间:2023-11-27 23:02:33 29 4
gpt4 key购买 nike

我正在尝试使用 vector 和指针实现我自己的链表。我遇到的问题是我无法让第一个节点指向第二个节点。

这是我的代码和我尝试过的:

struct Node {
Node* previous;
Node* next;

int data;
};

// Initialize: Create Vector size 20 and first node
void LinkedList::init() {
vecList.resize(20, NULL); // Vector of size 20
Node* head = new Node(); // Create head node
head->previous = NULL; // Previous point set to null
head->next = vecList[1]; // Next pointer set to next position
head->data = 0; // Data set at value 0

vecList[0] = head; // Put head node in first position
count = 1; // Increase count by 1
}

// Add Node to array
void LinkedList::push_back(Node* node, int data) {
count += 1;
node = new Node();
node->next = vecList[count + 1];
node->previous = vecList[count - 1];
node->data = data;
vecList[count - 1] = node;
}

数据已经传入,将使用:

cout << linkedlist.vecList[1]->data << endl;

但如果我尝试以这种方式显示,我会收到错误消息,指出下一个指针是 <Unable to read memory>

cout << linkedlist.vecList[0]->next->data << endl;

最佳答案

您忘记在push_back 方法中设置前一个Nodenext 指针。如果 count 是包含条目数的列表的成员变量,您必须像这样更改方法:

编辑:实际上你必须在最后增加 count 因为数组索引从零开始。

void LinkedList::push_back(Node * node, int data){  
node = new Node();
node->next = NULL; // NULL because next element does not exist yet
node->previous = vecList[count - 1];
node->data = data;
vecList[count] = node;
vecList[count-1]->next = vecList[count];
count++;
}

尝试用 vector 或数组实现链表还是有点奇怪,因为这实际上抵消了列表的优势...

关于c++ - 链表/vector 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26315282/

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