【发布时间】:2015-12-03 01:44:08
【问题描述】:
对于我的最终编程项目,我需要创建一个链表来保存项目,并且它需要能够删除和添加项目。将项目附加到链表工作正常,但是当我删除并尝试显示该功能时,程序在到达已删除项目所在的位置时崩溃。
假设第三项是被删除的那一项,它会像这样输出到屏幕上: 项目 1(显示) 项目 2(显示) 然后就崩溃了
因此,至少在我看来,当我使用删除功能时,它会在链表中留下某种“洞”。
当我从链表中删除时,它唯一不会崩溃的地方是头部,但出于某种奇怪的原因,之后链表中只剩下一项。
我想知道是否有人可以在我的删除功能或我的显示功能中指出导致此错误的位置。
//sending a number to the function holding the position of the item.
void InventoryList::deleteNode(int num)
{
ListNode *previousNode; //To point to the previous node
ListNode *nodePtr; //to traverse the list
int number = 1;
//if the head is empty do nothing
if (!head)
{
return;
}
//Determine if the first node is the value
if (1 == num)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
else
{
//intialize the node as head.
nodePtr = head;
//Skip nodes whose value is not equal to num.
while (nodePtr != nullptr && number != num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
number++;
}
if (nodePtr)
{
previousNode = nodePtr;
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
}
void InventoryList::displayList()
{
int x = 1;
//used to traverse the list
ListNode *nodePtr;
//setting the list equal tot he head
nodePtr = head;
//goes through the list
while (nodePtr)
{
//displaying the list.
cout << x << nodePtr->value << endl;
nodePtr = nodePtr->next;
x++;
}
}
【问题讨论】:
标签: c++ linked-list runtime