用链表搭建的栈与队列相对简单,队列的特点是先进先出,不啰嗦了,由于代码比较简单,相信光顾的人不会太多,下面直接贴代码。
头文件
1 #ifndef QUEUELI_H
2 #define QUEUELI_H
3
4 template<class T>
5 class Queue
6 {
7 public:
8 Queue();
9 ~Queue();
10
11 bool isEmpty() const;
12 const T & getFront() const;
13 void enqueue(const T& x);
14 T dequeue();
15 void makeEmpty();
16
17 private: //也可以做一个友元类
18 struct ListNode
19 {
20 T element;
21 ListNode *next;
22
23 ListNode(const T & theElement, ListNode *n=0):
24 element(theElement), next(n){}
25 };
26 ListNode *front;
27 ListNode *back;
28 };
29
30 template<class T>
31 Queue<T>::Queue() //创建队列
32 {
33 front = back = 0;
34 }
35
36 template<class T>
37 Queue<T>::~Queue()//所有步骤执行完最后执行析构函数,清空队列
38 {
39 makeEmpty();
40 }
41
42 template<class T>
43 void Queue<T>::makeEmpty()//清空队列
44 {
45 while (!isEmpty())
46 dequeue();
47 }
48
49 template<class T>
50 bool Queue<T>::isEmpty() const
51 {
52 return front == 0;
53 }
54
55 template<class T>
56 const T & Queue<T>::getFront() const
57 {
58 if (isEmpty())
59 throw"Queue is empty.";
60 return front->element;
61 }
62
63 template<class T>
64 void Queue<T>::enqueue(const T &x)
65 {
66 if (isEmpty())
67 back = front = new ListNode(x);
68 else
69 back = back->next = new ListNode(x);//队列在队尾插入结点
70 }
71
72 template<class T>
73 T Queue<T>::dequeue()//删除队列
74 {
75 T frontItem = getFront();//留作返回要删除的结点中的值用
76 ListNode *old = front;
77 front = front->next;
78 delete old;
79 return frontItem;
80 }
81
82 #endif
源文件-测试用
1 #include<iostream>
2 #include"QueueLi.h"
3
4 using namespace std;
5
6 int main()
7 {
8 cout << "测试链式队列:" << endl;
9
10 Queue<int> myQ;
11
12 myQ.enqueue(10);
13 myQ.enqueue(20);
14 myQ.enqueue(30);
15 myQ.enqueue(40);
16
17 cout << myQ.getFront() << endl;
18 myQ.dequeue();
19 cout << myQ.getFront() << endl;
20
21 return 0;
22 }