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

标签 c++ pointers vector linked-list

我正在尝试使用 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/

相关文章:

c++ - char s1[ ] = "xyz"和 char *s1 = "xyz"

vector - 无法通过索引访问向量中的可变引用

c++ - 作为类成员的 2D vector 指针

java - 从指针获取相关数据

c++ - 将 8 位数据作为 7 位数据访问

c++ - 我想获取用户输入并将其放入字符串数组 c++

c++ - 为什么我们需要第二个 std::forward 特化?

c++ - 在 C++ 中维护对任何对象类型的引用?

r - 如何交换R中命名向量的名称和值?

c++ - 访问指向结构中的值是否比访问本地值花费更多时间?