我正在编写一个链表,使用 vector 来保存(而且我知道我不应该使用 vector )。我正在尝试实现一个函数以将节点插入位置 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
.
节点
的定义:
struct Node {
Node * previous;
Node * next;
int id;
int data;
};
最佳答案
问题是你的循环:
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
会怎样?您将指向一个 undefined object 。
关于c++ - 在 vector 之后插入元素和移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26590697/