【发布时间】:2014-10-11 13:37:08
【问题描述】:
我正在尝试使用向量和指针来实现我自己的链表。我遇到的问题是我无法让第一个节点指向第二个节点。
这是我的代码和我尝试过的:
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;
【问题讨论】:
-
你怎么打电话给
LinkedList::push_back? -
什么是
LinkedList?vecList是什么?你如何使用代码?你得到什么错误? -
如果错误不是构建错误,那么您是否尝试过在调试器中逐行执行代码?
-
LinkedList 是类,vecList 是节点向量。我得到的错误是“访问冲突读取位置 0x00000008”。通过调试器并形成我可以看到的问题是我的指针没有指向任何东西
-
@ilent2 这就是我所说的:linkedlist.push_back(node, 64);它添加数据,但指向下一个和上一个的指针指向 notting
标签: c++ pointers vector linked-list