仿stl+函数模板

#include<iostream>
using namespace std;
template<class T>
void output(T begin, T end) {
  for (T p = begin; p != end; ++p) {
    cout << *p << " ";
  }
  cout << endl;
}
template<class T>
struct Node {//节点 
  T date;
  Node<T> *next;
  Node(){}
  Node(const T& x):date(x){}
};
template<class T>
class list_iterator{//迭代器类 
  public:
    typedef list_iterator<T> iterator;
    Node<T> *node;
    list_iterator(){}
    list_iterator(Node<T>* x):node(x){}
    bool operator!=(const iterator& x) {
      return node->date != x.node->date;
    }
    bool operator==(const iterator& x) {
      return node->date == x.node->date;
    }
    iterator& operator++() {
      node = node->next;
      return *this;
    }
    T& operator*(){
      return node->date;
    }
};

template<class T>
class List{//单项循环链表 
  private:
    Node<T>* head;
  public:
    typedef list_iterator<T> iterator;
    List(); 
    void push_back(const T& x);
    iterator begin()  { return head->next; }
    iterator end()  { return head; }
    void diaplay();
};
template<class T>
List<T>::List(){
  head = new Node<T>();
  head->next = head;
}

template<class T>
void List<T>::push_back(const T& x){
  Node<T> *p = head;
  while(p->next != head) {
    p = p->next;
  }
  Node<T> *s = new Node<T>(x) ;
  s->next = p->next;
  p->next = s;
}

template<class T>
void List<T>::diaplay(){
  Node<T> *p = head;
  while(p->next != head) {
    p = p->next;
    cout << p->date << " ";
  }
  cout << endl;
}
int main() {
  List<int> l;
  l.push_back(1);
  l.push_back(2);
  l.push_back(3);
  l.diaplay();
  cout << *(l.begin()) << endl;
  output(l.begin(),l.end());
} 

 

posted @ 2017-10-09 16:47  扫地の小沙弥  阅读(195)  评论(0编辑  收藏  举报