我不太精通C++,但我的任务是设计和实现一个链表。这是我交的:
template <typename T>
struct Node
{
Node() : next(nullptr) {}
Node(T const & val) : next(nullptr), value(val) {}
Node * next;
T value;
};
template <typename T>
class LinkedList
{
public:
LinkedList()
{
begin_ = new Node<T>;
current_ = begin_;
}
~LinkedList()
{
delete begin_;
}
void insert(T const & value)
{
Node<T> * node = new Node<T>(value);
node->next = current_->next;
current_->next = node;
current_ = current_->next;
}
void remove()
{
Node<T> * tmp = current_->next;
if(!end())
{
current_->next = current_->next->next;
}
delete tmp;
}
bool end() const
{
return current_->next == nullptr;
}
void reset()
{
current_ = begin_;
}
void advance()
{
if(!end())
{
current_ = current_->next;
}
}
T get() const
{
return current_->next->value;
}
private:
Node<T> * begin_;
Node<T> * current_;
};
我通过了作业,但我的老师delete begin_
在析构函数中划了下划线~LinkedList()
并写了“这泄漏了!” 在它的旁边。我一直在想怎么delete begin_
可能泄漏,但我还是不明白。有人可以帮我吗?