C++通用链表和迭代器
C++ Generic Linked List and Iterator
我刚开始学习C++,需要编写一个通用链表和迭代器。这是我写的代码(list.h
),但我认为它不正确。它不起作用,我不确定它是否通用。
#include <iostream>
#include <cassert>
using namespace std;
using namespace ListExceptions;
class List;
class Iterator;
template<class T>
class Node{
private:
T data;
Node* previous;
Node* next;
friend class List;
friend class Iterator;
public:
Node(T element){
data = element;
previous = NULL;
next = NULL;
}
};
class List{
private:
Node* first;
Node* last;
public:
List(){
first = NULL;
last = NULL;
}
void pushBack(T element);
void insert(Iterator iter, T element);
Iterator remove(Iterator i);
Iterator find(const Predicate& predicate);
void sort(const Compare& comparer);
int getSize() const;
Iterator begin();
Iterator end();
};
class Iterator{
private:
Node* position;
Node* last;
friend class List;
public:
Iterator();
void next();
T getElement()const;
bool equals(Iterator b) const;
bool notEquals(Iterator b) const;
};
如果有人能帮我?
首先,List
和Iterator
是非模板类,您可能想要创建给定类型的List
。您可以考虑重构代码,使Node
和Iterator
都是List
类型的内部类(这会使事情变得更简单):
template <typename T>
class List {
public:
typedef T value_type;
class Iterator;
struct Node { // Internal to List<T>, so there will be different
// List<T>::Node for each instantiationg type T
// But you don't need the extra <T> parameter for List
// or Iterator
value_type data;
Node* next;
Node* last;
friend class List; // Inside List<T>, List by itself refers to List<T>
friend class Iterator;
};
//...
};
替代方案的代码稍微复杂一点:
template <typename T> class List;
template <typename T> class Iterator;
template <typename T> class Node {
T data;
Node * next;
Node * last;
friend class List<T>;
friend class Iterator<T>;
};
template <typename T>
class List {
Node<T>* first; // note <T> required
//...
};
相关文章:
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- C++嵌套的迭代器类(在链表类中)Insert_After函数
- std::filesystem::directory_迭代器链接器问题(C++17)
- C++链表最后一个元素的迭代器?
- 如何实现双向链表的迭代器?
- 使用迭代从链表向后打印字符串
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- 在链表上实现随机访问迭代器
- 后缀运算符链表泛型节点迭代器
- 链表迭代器实现C++
- 迭代器作为 C++ 中链表类之外的单独类
- 链表常量迭代器
- 双链表迭代器实现的问题
- 链表迭代器模板中的编译错误
- 迭代器实现 -(链表队列)
- 返回链表的正确迭代器类型
- C++链表迭代器类
- 需要帮助编码迭代器的循环链表在c++
- C++通用链表和迭代器
- 自定义双链表迭代器