如何删除上一个节点?

How to delete previous node?

本文关键字:上一个 节点 删除 何删除      更新时间:2023-10-16

我想了解有关链表的更多信息,因为现在我只能添加,显示和删除最后一个节点以及除按其ID删除之外的所有节点。所以现在我想学习如何通过这种方法按其ID删除,但是这个方法无法删除第一个节点。在我看来,此方法无法删除以前的节点。所以我尝试删除以前的节点,但它不起作用。

void carInsurance::deletebyPaymentID(int *x)
{
// to remove an element, we go through the list, find the value given
// if we find it, stop
// to remove, disconnect the link
// relink the two values now (ie. value 1->2->3->NULL, 2 is removed, 1->3->NULL )
int remValue=*x;
carInsurance* prev = start_ptr; // empty header
carInsurance* current = start_ptr->next; // the first valid node
while(current != NULL)
{
if(current->paymentID == remValue)
{
break;
}
else
{
prev = current;
current = current->next; // To go to next value
}
}
if(current == NULL)
{ // if end of list is reached or the list is empty
cout << "No match found!n";
}
else
{
cout << "Deleting: " << current << "n";
prev->next = current->next; // To unlink the node you remove
delete current; // To delete the node
//cout << "Customer with payment ID "<< remValue << " has been deletedn"; // To inform user successfully deleted
}
}

我已经解决了这个问题。代码只需要第一个节点的特殊情况:

if( prev->paymentID == remValue)
{
cout << "Deleting: " << remValue << "n";
prev = start_ptr; // unlink the node you remove
start_ptr = start_ptr->next;
free(prev); // delete the first node
break;
}

我假设你想知道这些数据结构是如何工作的,否则,我同意@ron - 使用 STL 列表实现。

有很多方法可以解决这个"删除根"问题,可以在一本好书中找到。
一种方法是,您的 prev 指针实际上并不指向上一个节点本身,而是指向前一个节点的下一个指针。对于第一个节点,它指向容器的根指针。
另一种方法是容器有一个虚拟节点实例,它充当根指针和列表的两端。
这两种解决方案都意味着您不需要特定的代码来处理列表末尾的特殊情况。