练习之<链表>
LinkList类
View Code
1 //LinkList类
2 template<class Type>class LinkList
3 {
4 private:
5 struct Node
6 {
7 Node *Next;
8 Type data;
9 }*Head,*Tail;
10 unsigned int size;
11 public:
12 LinkList()
13 {
14 Head=new Node;
15 Head->Next=NULL;
16 Head->data=0;
17 Tail=Head;
18 size=0;
19 }
20 ~LinkList();
21 void push_back(Type data);
22 ostream& operator<<(ostream &os);//输入链表中的元素
23 };
24
25 template<class Type> LinkList<Type>::~LinkList()
26 {
27 Node *cur=Head;
28 Node *temp=cur->Next;
29 while(cur!=NULL)
30 {
31 delete cur;
32 cur=temp;
33 if(temp!=NULL)
34 temp=temp->Next;
35 }
36 }
37 template<class Type> void LinkList<Type>::push_back(Type data)
38 {
39 Node *node = new Node;
40 node->data=data;
41 node->Next=Tail->Next;
42 Tail->Next=node;
43 Tail=node;
44 ++size;
45 }
46 template<class Type> ostream& LinkList<Type>::operator<<(ostream &os)
47 {
48 Node *cur=Head->Next;
49 while(cur!=NULL)
50 {
51 os<<cur->data<<" ";
52 cur=cur->Next;
53 }
54 os<<endl;
55 return os;
56 }