stl的list是双向链表,有一个节点是End节点,End节点的next是链表的起始节点,最后一个节点的next指向End节点,这样begin函数的创建是传入End节点的next,而end函数返回的迭代器内部保存的是End节点。
下面实现一个简单的单向链表,end迭代器中是NULL指针,标志结束。
#include <stdio.h>
template<typename T>
class ListNode {
public:
ListNode(const T& value) : value_(value), next_(NULL) {}
ListNode(ListNode* previous, const T& value) : value_(value), next_(NULL) {
if (previous) {
previous->next_ = this;
}
}
T value_;
ListNode* next_;
};
template<typename T, typename VisitFun>
class List {
public:
class Iterator {
public:
Iterator(ListNode<T>* list_node) : current_(list_node) {}
T& operator*() {
return current_->value_;
}
const T& operator*() const {
return current_->value_;
}
T* operator->() {
return ¤t_->value_;
}
const T* operator->() const {
return ¤t_->value_;
}
Iterator& operator++() {
current_ = current_->next_;
return *this;
}
Iterator operator++(int) {
Iterator tmp = *this;
current_ = current_->next_;
return tmp;
}
bool operator !=(const Iterator& right) const {
return current_ != right.current_;
}
ListNode<T>* current_;
};
List() : head_(NULL), tail_(NULL) {}
Iterator Begin() {
Iterator it(head_);
return it;
}
Iterator End() {
Iterator it(NULL);
return it;
}
void PushBack(const T& value) {
if (tail_) {
tail_ = new ListNode<T>(tail_, value);
} else {
tail_ = new ListNode<T>(value);
head_ = tail_;
}
}
void Print(VisitFun visit_fun) {
Print(head_, visit_fun);
}
private:
void Print(ListNode<T>* current, VisitFun visit_fun) {
if (current) {
Print(current->next_, visit_fun);
visit_fun(current->value_);
}
}
ListNode<T>* head_;
ListNode<T>* tail_;
};
void PrintInt(int value) {
printf("%d ", value);
}
typedef void (*PrintFun)(int );
int main(int argc, char** argv) {
List<int, PrintFun> my_list;
for (int i = 0; i < 100; ++i) {
my_list.PushBack(i);
}
my_list.Print(PrintInt);
printf("\n");
for (List<int,PrintFun>::Iterator it = my_list.Begin(); it != my_list.End(); ++it) {
printf("%d ", *it);
}
}