[英]C++ Generic Linked List and Iterator
I've just started with learning C++ and I need to write a generic linked list and iterator. 我刚刚开始学习C ++,我需要编写一个通用的链表和迭代器。 This is the code that I wrote ( list.h
), but I think it is not correct. 这是我编写的代码( list.h
),但我认为这是不正确的。 It does not work and I am not sure that it is generic. 它不起作用,我不确定它是否通用。
#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;
};
If someone can help me? 如果有人可以帮助我?
First thing is that the List
and Iterator
are non-templated classes, and you probably want to create List
s of a given type. 第一件事是List
和Iterator
是非模板类,您可能想创建给定类型的List
。 You might consider refactoring the code so that both the Node
and the Iterator
are internal classes to the List
type (it will make things simpler): 您可能考虑重构代码,以便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;
};
//...
};
The alternative is a little more complex in code: 替代方法在代码上稍微复杂一些:
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
//...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.