标签:tle -- color private head return visit int search
sLinkList模板类,单链表代码
1 /* 2 该文件按习惯可以分成.h文件和实现的.cpp文件 3 */ 4 template <class elemType> 5 class sLinkList 6 { 7 private: 8 struct node{ //定义单链表中的结点结构 9 elemType data; 10 node *next; 11 12 node(const elemType &x, node *n = NULL) 13 { 14 data = x; next = n;; 15 } 16 node() :next(NULL) {} 17 ~node() {} 18 }; 19 20 node *head;//头指针 21 int currentLength;//表长 22 23 //node *move(int i)const;//返回第i个结点的地址 24 node *move(int i)const 25 { 26 node *p = head; 27 while( i-- >= 0 ) 28 { 29 p = p->next; 30 } 31 return p; 32 } 33 34 public: 35 sLinkList(); 36 ~sLinkList() { 37 clear(); delete head; 38 } 39 40 void clear(); 41 int length()const { 42 return currentLength; 43 } 44 void insert(int i, const elemType&x); 45 void remove(int i); 46 int search(const elemType&x)const; 47 elemType visit(int i)const; 48 void traverse()const; 49 }; 50 51 // sLinkList 52 template <class elemType> 53 sLinkList<elemType> ::sLinkList() 54 { 55 head = new node; 56 currentLength = 0; 57 } 58 59 // clear 60 template <class elemType> 61 void sLinkList<elemType> ::clear() 62 { 63 node *p = head->next, *q; 64 head->next = NULL; 65 while(p!=NULL) 66 { 67 q = p->next; 68 delete p; 69 p = q; 70 } 71 currentLength = 0; 72 } 73 74 // insert 75 template <class elemType> 76 void sLinkList<elemType> ::insert(int i, const elemType&x) 77 { 78 node *pos; 79 pos = move(i-1); 80 pos->next = new node(x, pos->next); 81 ++currentLength; 82 } 83 84 /* // 类外实现,编译器编译不过,只好类内实现 85 // move 86 template <class elemType> 87 sLinkList<elemType>::node *sLinkList<elemType> :: move(int i)const 88 { 89 node *p = head; 90 while( i-- >= 0 ) 91 { 92 p = p->next; 93 } 94 return p; 95 } */ 96 97 // search 98 template <class elemType> 99 int sLinkList<elemType> :: search(const elemType&x)const 100 { 101 node *p = head->next; 102 int i=0; 103 while( p != NULL && p->data != x ) 104 { 105 p = p->next; 106 ++i; 107 } 108 109 if(p == NULL) 110 return -1; 111 else 112 return i; 113 } 114 115 // visit 116 template <class elemType> 117 elemType sLinkList<elemType> :: visit(int i)const 118 { 119 return move(i)->data; 120 } 121 122 // traverse 123 template <class elemType> 124 void sLinkList<elemType> :: traverse()const 125 { 126 node *p = head->next; 127 cout<<endl; 128 129 while( p != NULL ) 130 { 131 cout<<p->data<<" "; 132 p = p->next; 133 } 134 135 cout<<endl; 136 } 137 138 // remove 139 template <class elemType> 140 void sLinkList<elemType> :: remove(int i) 141 { 142 node *pos, *delp; 143 pos = move(i-1); 144 delp = pos->next; 145 146 pos->next = delp->next; 147 delete delp; 148 149 --currentLength; 150 }
标签:tle -- color private head return visit int search
原文地址:https://www.cnblogs.com/GoldenEllipsis/p/10592918.html