本文实例为大家分享了用模板实现单链表,供大家参考,具体内容如下
话不多说 直接上代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
#include <iostream> using namespace std; template < typename E> class CLink; template < typename T> class Node { friend class CLink<T>; public : /* 构造函数和析构函数一般不加类型参数 本类类中除了构造函数和析构函数以外 其它的地方都要加上类型参数 */ Node(T data = 0) { mdata = data; pnext = NULL; } ~Node(){} private : T mdata; Node<T>* pnext; }; template < typename T> class CLink { public : CLink() { phead = new Node<T>(); } void InsertHead(T data) { Node<T>* pNewNode = new Node<T>(data); pNewNode->pnext = phead->pnext; phead->pnext = pNewNode; } void InsertTail(T data) { Node<T>* pNewNode = new Node<T>(data); Node<T>* pCur = phead; while (pCur->pnext != NULL) { pCur = pCur->pnext; } pCur->pnext = pNewNode; } void Show() { Node<T>* pCur = phead->pnext; while (pCur != NULL) { cout << pCur->mdata << " " ; pCur = pCur->pnext; } cout << endl; } ~CLink() { Node<T>* pCur = phead; Node<T>* pNext = phead; while (pCur != NULL) { pNext = pCur->pnext; delete pCur; pCur = pNext; } phead = NULL; } private : Node<T>* phead; }; int main() { CLink< int > list1; CLink< int > list2; for ( int i = 0;i < 10;i++) { list1.InsertHead(i + 1); list2.InsertTail(i * 2); } cout << "list1:" ; list1.Show(); cout << "list2:" ; list2.Show(); return 0; } |
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/MOON5555/article/details/79158994