2014-10-11 94 views
0

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

这里是我的代码和我已经试过:

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; 
+0

你是如何调用'链表:: push_back' ? – ilent2 2014-10-11 13:41:57

+2

什么是'LinkedList'?什么是'vecList'?你如何使用代码?你会得到什么错误? – 2014-10-11 13:42:16

+0

如果错误不是编译错误,那么您是否尝试在调试器中逐行执行代码? – 2014-10-11 13:43:17

回答

2

您忘记在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++; 
} 

不过这是一个有点奇怪,你试图实现与向量或数组链表,因为实际上违背了列表的优势...

+1

谢谢你排序我的问题:)至于为什么我用矢量来存储列表你可以问我的讲师 – 2014-10-11 14:03:57

2

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

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

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

但在这一点上,第二个元素还不存在。所以你不能指出它。在push_back函数中类似的错误。