链表/向量中的指针

时间:2014-10-11 13:37:09

标签: c++ pointers vector linked-list

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

这是我的代码以及我尝试过的内容:

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;

2 个答案:

答案 0 :(得分:2)

看起来vecList是指向Node的指针的向量/数组。

初始化时,让第一个元素指向第二个元素:

void LinkedList::init(){
    ...
    head->next = vecList[1]; 

但此时,第二个元素尚不存在。所以你还不能指出它。 push_back函数有类似的错误。

答案 1 :(得分:2)

您忘记在next方法中设置上一个Node的{​​{1}}指针。 如果push_back是包含条目数的列表的成员变量,则必须更改方法,如下所示:

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

count

您尝试使用向量或数组实现链接列表仍然有点奇怪,因为这实际上违背了列表的优点......