如何删除上一个节点?
How to delete previous node?
我想了解有关链表的更多信息,因为现在我只能添加,显示和删除最后一个节点以及除按其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 指针实际上并不指向上一个节点本身,而是指向前一个节点的下一个指针。对于第一个节点,它指向容器的根指针。
另一种方法是容器有一个虚拟节点实例,它充当根指针和列表的两端。
这两种解决方案都意味着您不需要特定的代码来处理列表末尾的特殊情况。
相关文章:
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 在C++的链表末尾插入一个节点
- 在单链表前面添加一个节点后,我无法遍历每个节点
- 删除链接列表中剩余的最后一个节点
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 类模板上一个特定函数的未解析外部符号
- 错误:"int pow(double,int)"与上一个声明int pov(double a,int
- 如何查看提升集中<cpp_int>的下一个和上一个元素
- C++循环链表删除,计数从下一个节点开始
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- 如何删除上一个节点?
- 插入指针数组会删除上一个结果
- 添加一个节点,并在通用树中的两个给定节点之间找到路径成本,其中c 中的儿童列表
- 助推器使用上一个DMATRIX后,XGDMATRIXCREATEFROMMAT失败
- 我试图键入一个函数来在单链表的末尾添加一个节点,但不起作用
- 尝试指向链表中的上一个节点
- C++为什么创建一个新节点来删除堆栈上的节点是错误的
- 拥有带有InfiniBand的Windows Azure A8节点支持如何从一个节点发送N个字节并在另一个节点上接收
- 尝试将上一个节点链接到要删除的节点之后的节点时出错
- 访问std::列表上的最后一个节点