C++ 删除类似的节点链表
c++ remove similar nodes linked list
对于家庭作业,我需要删除该数字传入的所有类似节点。例如,如果我在列表中
355四
5 将从链表中删除,我将以
3四
我们不允许将 std 库用于此类,这里是头文件
namespace list_1
{
class list
{
public:
// CONSTRUCTOR
list( );
// postcondition: all nodes in the list are destroyed.
~list();
// MODIFICATION MEMBER FUNCTIONS
//postcondition: entry is added to the front of the list
void insert_front(const int& entry);
//postcondition: entry is added to the back of the list
void add_back(const int& entry);
// postcondition: all nodes with data == entry are removed from the list
void remove_all(const int& entry);
// postcondition: an iterator is created pointing to the head of the list
Iterator begin(void);
// CONSTANT MEMBER FUNCTIONS
// postcondition: the size of the list is returned
int size( ) const;
private:
Node* head;
};
}
我可以理解如何删除列表的正面和背面。但是由于某种原因,我无法浏览列表并删除所有传入的数字。什么都有帮助!谢谢
编辑以包含 Node.h
#pragma once
namespace list_1
{
struct Node
{
int data;
Node *next;
// Constructor
// Postcondition:
Node (int d);
};
}
有两种方法可以做到这一点。第一种是循环访问列表并删除节点。这很棘手,因为要做到这一点,您必须保留指向前一个节点的指针,以便您可以更改其next
值。用于删除节点的代码如下所示(假设current
是当前节点,prev
是上一个节点)
Node* next = current->next;
delete current;
prev->next = next;
不过,维护对前一个节点的引用可能有点乏味,因此这是另一种方法。在此方法中,您实质上创建一个新列表,但不插入data
等于 entry
的节点。
代码可能看起来有点像这样
void list::remove_all(const int &entry)
{
Node* newHead = NULL;
Node* newTail = NULL;
Node* current = head;
// I'm assuming you end your list with NULL
while(current != NULL)
{
// save the next node in case we have to change current->next
Node* next = current->next;
if (current->data == entry)
{
delete current;
}
else
{
// if there is no head, the set this node as the head
if (newHead == NULL)
{
newHead = current;
newTail = current;
newTail->next = NULL; // this is why we saved next
}
else
{
// append current and update the tail
newTail->next = current;
newTail = current;
newTail->next = NULL; // also why we saved next
}
}
current = next; // move to the next node
}
head = newHead; // set head to the new head
}
注意:我没有测试这个,我只是在头顶上输入了它。确保它有效。=)
希望这有帮助! ;)
相关文章:
- 反向给定链表中的K节点
- 我们可以删除链表中静态内存中的节点吗
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 如何按数字顺序插入链表节点?
- 为什么我的双向链表删除函数会删除多个节点?
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 在C++的链表末尾插入一个节点
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 插入一个基本的单向链表节点似乎破坏了我的 c++ 代码?
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 删除链表中的特定节点
- 在 c++ 中,在链表节点上使用括号有什么意义?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 删除链表中的节点 - 分段错误
- 使用函数引用指向节点的指针删除链表中的节点?
- 节点链表中的对象
- 虚拟头节点链表
- C++ 删除类似的节点链表
- c++删除节点链表导致程序崩溃
- 排序节点(链表)c++