2014-10-11 81 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函數中類似的錯誤。