循环链表以及迭代器的使用c++

循环链表,顺便也附上链表的迭代器

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 template<class T> class List;
  6 template<class T> class ListIterator;
  7 
  8 template<class T>
  9 class ListNode
 10 {
 11     friend class List<T>;
 12     friend class ListIterator<T>;
 13 private:
 14     T data;
 15     ListNode *Link;
 16     ListNode(T);
 17     ListNode(){}
 18 };
 19 
 20 template<class T>
 21 ListNode<T>::ListNode(T element)
 22 {
 23     data = element;
 24     Link = 0;
 25 }
 26 
 27 template<class T>
 28 class List
 29 {
 30     friend class ListIterator<T>;
 31 public:
 32     List(){first=new ListNode<T>; first->Link=first;}
 33     void Insert(T);
 34     void Delete(T);
 35 private:
 36     ListNode<T> *first;
 37 };
 38 
 39 template<class T>
 40 class ListIterator
 41 {
 42 public:
 43     ListIterator(const List<T>& l):mylist(l),current(l.first->Link){}
 44     bool NotNull();
 45     bool NextNotNull();
 46     T* First();
 47     T* Next();
 48 private:
 49     const List<T> &mylist;
 50     ListNode<T>* current;
 51 };
 52 
 53 template<class T>
 54 bool ListIterator<T>::NotNull()
 55 {
 56     if(current != mylist.first) return true;
 57     else return false;
 58 }
 59 
 60 template<class T>
 61 bool ListIterator<T>::NextNotNull()
 62 {
 63     if(current->Link != mylist.first) return true;
 64     else return false;
 65 }
 66 
 67 template<class T>
 68 T* ListIterator<T>::First()
 69 {
 70     if(NotNull()) return &current->data;
 71     else return 0;
 72 }
 73 
 74 template<class T>
 75 T* ListIterator<T>::Next()
 76 {
 77     current = current->Link;
 78 //    if(current==mylist.first)current=current->Link;
 79     return &current->data;
 80 }
 81 
 82 template<class T>
 83 void List<T>::Insert(T x)
 84 {
 85     ListNode<T> *newNode=new ListNode<T>(x);
 86     newNode->Link = first->Link;
 87     first->Link = newNode;
 88 }
 89 
 90 template<class T>
 91 void List<T>::Delete(T k)
 92 {
 93     ListNode<T> *previous = first;
 94     ListNode<T> *current;
 95     for(current=first->Link; (current!=first)&&(current->data!=k);
 96         previous=current, current=current->Link);
 97     if(current!=first)
 98     {
 99         previous->Link = current->Link;
100         delete current;
101     }
102 }
103 
104 int main()
105 {
106     cout << "Hello world!" << endl;
107 
108     List<int> intlist;
109     intlist.Insert(5);
110     intlist.Insert(15);
111     intlist.Insert(25);
112     intlist.Insert(35);
113 
114     ListIterator<int> myl(intlist);
115     if(myl.NotNull())
116     {
117         cout << *myl.First()*10;
118         while(myl.NextNotNull())
119               cout << "->" << *myl.Next()*10;
120         cout << endl;
121     }
122 
123     return 0;
124 }
原文地址:https://www.cnblogs.com/yang901112/p/12493837.html