2014-10-27 61 views
2

我正在使用向量來寫入鏈接列表(並且我知道我不應該使用向量)。我試圖實現一個函數來插入節點x並移動所有元素後x,但由於某種原因,它只需要原來在x和以上的元素寫入所有其餘元素與此值。在向量中插入元素並移動元素

這是我有問題的功能:

//Insert element at x index 
void LinkedList::insertAt(int x, int data) { 
    Node* tempNode = new Node(); 
    Node* currentNode = vecList[x]; 
    Node* nextNode = vecList[x + 1]; 
    Node* previousNode = vecList[x - 1]; 

    if(x == count) { 
     push_back(tempNode, data); 
     return; 
    } 
    else { 
     count++; 
     for (int i = 0; i < getSize(); i++){ 
      vecList[x + 1]->next = vecList[x]->next; // tranfer the address of 'temp->next' to 'temp' 
      vecList[x + 1]->data = vecList[x]->data; 
      if (vecList[x] == NULL){break;} 
     } 
     tempNode->data = data; 
     tempNode->previous = previousNode; 
     tempNode->next = nextNode; 
     tempNode->id = x+1; 

     vecList[x] = tempNode; 
     vecList[x - 1]->next = tempNode; //Point previous node to this node 
    } 
}//Adds Node but replaces orignal Node 

它把傳遞到x位置的值,我覺得我的問題是x後移動的元素。

當我打電話給linkedlist.insertAt(2, 50);,它的做法是:10, 20, 50, 30, 30,但預計:10, 20, 50, 30 ,40

Node定義:

struct Node { 
    Node * previous; 
    Node * next; 

    int id; 
    int data; 
}; 
+1

只是爲了完整性,你能告訴我們'節點'的定義嗎?除此之外,我只想評論一下,這是一個針對(表面上)作業問題的非常好的問題 - 它顯示了代碼存在問題,你做了什麼,期望的輸出和實際的輸出。其他有作業問題的學生會很好地模仿這個問題。 – cdhowie 2014-10-27 15:15:52

+0

加入了'Node'的定義..雅是上週的家庭作業和bin竊聽我,所以我說我會嘗試在這裏尋求幫助 – 2014-10-27 15:21:00

+4

循環看起來錯了,它在'i'上循環,但是'i'永遠不會引用。 – Ylisar 2014-10-27 15:21:28

回答

0

的問題是你的循環:

for (int i = 0; i < getSize(); i++){ 
    vecList[x + 1]->next = vecList[x]->next; // tranfer the address of 'temp->next' to 'temp' 
    vecList[x + 1]->data = vecList[x]->data; 
    if (vecList[x] == NULL){break;} 
} 

你遍歷i,但沒有在循環實際讀取i。所以你只是做相同的操作getSize()次。我想你打算將vecList[i + 1]指定爲veclist[i]。此外,循環的下限不應該是0,它應該是x。其中,爲了進一步明確,該變量的名稱可能應該是pos或類似的東西。

當你參考vecList[x + 1]vecList[x - 1]時也要小心。如果x爲0或vecList.size() - 1會怎麼樣?您將指向一個未定義的對象。