不使用循环,采用头尾指针,不带有头结点,我这里只是简易的输出,并没有写专用的迭代器。
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> class MyList; 6 7 template<class T> 8 class ListNode 9 { 10 friend class MyList<T>; 11 private: 12 T data; 13 ListNode *Link; 14 ListNode(const T &thedata){data = thedata; Link=0;} 15 ListNode(){} 16 }; 17 18 template<class T> 19 class MyList 20 { 21 public: 22 MyList(){first = new ListNode<T>;first->Link=NULL;tail=first;} 23 ~MyList(){MakeEmpty();} 24 void MakeEmpty(); 25 bool IsEmpty(); 26 void Insert(const T &); 27 void Delete(const T &); 28 void Invert(); 29 void Concatenate(MyList<T>); 30 void Show(); 31 private: 32 ListNode<T> *first; 33 ListNode<T> *tail; 34 }; 35 36 template<class T> 37 bool MyList<T>::IsEmpty() 38 { 39 return first == 0; 40 } 41 42 template<class T> 43 void MyList<T>::MakeEmpty() 44 { 45 ListNode<T> *p=first; 46 while(first) 47 { 48 p = first; 49 first = first->Link; 50 delete p; 51 } 52 } 53 54 template<class T> 55 void MyList<T>::Insert(const T &x) 56 { 57 ListNode<T> *newNode = new ListNode<T>(x); 58 newNode->Link=tail->Link; 59 tail->Link = newNode; 60 tail = newNode; 61 } 62 63 template<class T> 64 void MyList<T>::Delete(const T &k) 65 { 66 if(IsEmpty()) return; 67 ListNode<T> *previous=0; 68 ListNode<T> *current; 69 for(current=first;current&¤t->data!=k; 70 previous=current,current=current->Link); 71 if(current) 72 { 73 if(previous) previous->Link=current->Link; 74 else first->Link=tail; 75 delete current; 76 } 77 } 78 79 template<class T> 80 void MyList<T>::Invert() 81 { 82 ListNode<T> *p=first->Link, *q=0; 83 while(p) 84 { 85 ListNode<T> *r = q; q = p; 86 p = p->Link; 87 q->Link = r; 88 } 89 first->Link = q; 90 } 91 92 template<class T> 93 void MyList<T>::Concatenate(MyList<T> List2) 94 { 95 if(!first) {first = List2.first;} 96 if(List2.first) 97 { 98 ListNode<T> *p; 99 for(p=first; p->Link; p=p->Link); 100 p->Link = List2.first->Link; 101 } 102 } 103 104 105 template<class T> 106 void MyList<T>::Show() 107 { 108 ListNode<T> *current; 109 for(current=first->Link; current; current=current->Link) 110 { 111 cout << current->data; 112 if(current->Link) cout << "->"; 113 } 114 cout << endl; 115 } 116 117 int main() 118 { 119 MyList<int> intlist; 120 intlist.Insert(5); 121 intlist.Insert(15); 122 intlist.Insert(25); 123 intlist.Insert(35); 124 intlist.Invert(); 125 MyList<int> intlist2; 126 intlist2.Insert(45); 127 intlist.Concatenate(intlist2); 128 intlist.Show(); 129 intlist.Delete(35); 130 intlist.Delete(25); 131 intlist.Delete(15); 132 intlist.Delete(6); 133 134 intlist.Show(); 135 // cout << "Hello world!" << endl; 136 return 0; 137 }