【数据结构梳理05】链表的一种迭代器

迭代器是一种用来一个一个地获取容器类中所有元素的对象,在数据结构课程中我们经常需要遍历或获取数据结构中所存储的数据,使用迭代器能大大方便我们的操作。

下面我们来介绍单向链表的一种前向迭代器。

注意:该迭代器需要作为自定义链表类的公共成员,即声明为嵌套公共类。

class ChainIterator{
public:
  ChainIterator(ChainNode<T>* startNode = 0) { current = startNode; }
  T* operator*()const {return current->data;}
  T& operator->()const {return &current->data;}
  ChainIterator operator++(){
    current=current->link;
    return *this;
  }
  ChainIterator operator++(int){
    ChainIterator old=*this;
    current=current->link;
    return *this;
  }
  bool operator != (const ChainIterator right) const { return current != right.current; }
  bool operator == (const ChainIterator right) const { return current == right.current; }
  ChainIterator begin() {return ChainIterator(first);}
  ChainIterator end() {return ChainIterator(0);}
  
private:
  ChainNode<T>* current; 
};
    
posted @ 2021-12-08 15:41  天涯海角寻天涯  阅读(93)  评论(0)    收藏  举报