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;
};
只是爲了完整性,你能告訴我們'節點'的定義嗎?除此之外,我只想評論一下,這是一個針對(表面上)作業問題的非常好的問題 - 它顯示了代碼存在問題,你做了什麼,期望的輸出和實際的輸出。其他有作業問題的學生會很好地模仿這個問題。 – cdhowie 2014-10-27 15:15:52
加入了'Node'的定義..雅是上週的家庭作業和bin竊聽我,所以我說我會嘗試在這裏尋求幫助 – 2014-10-27 15:21:00
循環看起來錯了,它在'i'上循環,但是'i'永遠不會引用。 – Ylisar 2014-10-27 15:21:28