单向链表的创建与迭代访问

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 &current_->value_;
    }
    const T* operator->() const {
      return &current_->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);
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值