gpt4 book ai didi

c++ - linkedList remove_all 函数

转载 作者:行者123 更新时间:2023-11-28 07:37:02 25 4
gpt4 key购买 nike

我正在编写列表和迭代器类函数,我几乎完成了,但是我在主文件中遇到了一些错误,当我编写列表 remove_all 函数时,但是当我删除它时,任何地方都没有错误,我不知道为什么!!另外,实际上我不确定我的 Iterator 运算符和 bool Iterator::is_item()

感谢任何帮助。谢谢

这是我的代码:

节点.h

pragma once

namespace list_1
{
template <typename T>
struct Node
{
T data;
Node<T> *next;


// Constructor
// Postcondition:
Node<T> (T d);
};

template <typename T>
Node<T>::Node(T d)
{

}
}

迭代器.h

// Template CLASS PROVIDED: Iterator 

#pragma once
#include "Node.h"

namespace list_1
{
template<typename T>
class Iterator
{
public:
Iterator<T> (Node<T> *np);
// precondition: is_item is true
// post condition n points to the next item in the list
void operator++();
// precondition:
// postcondition: returns true if there is a valid item
bool is_item();
// precondition: is_item == true
// postcondition returns data that n is pointing at
T operator* ();

private:
Node<T>* n;

};

列表.h

#ifndef LIST_H
#define LIST_H
#include "Node.h"
#include "Iterator.h"

namespace list_1
{
template <typename T>
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 T& entry);
//postcondition: entry is added to the back of the list
void add_back(const T& entry);
// postcondition: all nodes with data == entry are removed from the list
void remove_all(const T& entry);
// postcondition: an iterator is created pointing to the head of the list
Iterator<T> begin(void);

// CONSTANT MEMBER FUNCTIONS
// postcondition: the size of the list is returned
int size( ) const;
private:
Node<T>* head;

};

最佳答案

您的语法错误是因为您在 remove_all 函数末尾的“else” block 上缺少一对右花括号。

尝试用这个替换它

(编辑:包括上面评论中提到的关于 cout 的建议)

void list<T>::remove_all(const T& entry)
{
if(head == 0)
{
std::cout<<" node cannot be delted";

}
else
{
Node<T> *curr = head;
Node<T> *trail = 0;

while( curr != 0)
{
if(curr->entry == entry)
{
break;
}
else
{
trail = curr;
curr = curr->next;
}
}
if(curr == 0)
{
std::cout<<" Node " << entry<< " is not found";
}
else
{
if ( head == curr)
{
head = head->next;
}
else
{
trail->next = curr->next;
}
} // missing this one
delete curr;
} // and this one as well
}

关于c++ - linkedList remove_all 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16600341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com