-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoopQueue.cpp
122 lines (106 loc) · 2.15 KB
/
LoopQueue.cpp
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//
// main.cpp
// LoopQueue
//
// Created by 余彬 on 16/4/19.
// Copyright © 2016年 余彬. All rights reserved.
//
#include <iostream>
using namespace std;
template <class T>
class Node {
public:
T data;
Node<T> *pNext;
};
template <class T>
class Queue {
public:
Queue();
int shift(T data);
T unshift();
void show(int n);
void clear();
private:
Node<T> * pHead;
Node<T> * pRear;
int lenght;
};
template <class T>
Queue<T>::Queue(){
this->pHead = this->pRear = new Node<T>;
this->pRear->pNext = this->pHead;
this->lenght = 0;
}
template <class T>
int Queue<T>::shift(T data){
if(this->lenght == 0){
this->pHead->data = data;
}else{
Node<T> *pNew = new Node<T>;
pNew->pNext = this->pHead;
pNew->data = data;
this->pRear->pNext = pNew;
this->pRear = pNew;
}
return ++this->lenght;
}
template <class T>
T Queue<T>::unshift(){
T result;
if(this->lenght > 0){
Node<T> * pDel;
result = this->pHead->data;
pDel = this->pHead;
this->pHead = this->pHead->pNext;
this->pRear->pNext = this->pHead;
delete pDel;
this->lenght--;
if(this->pHead == NULL){
this->pHead = this->pRear;
}
}
return result;
}
template <class T>
void Queue<T>::show(int n){
Node<T> * p = this->pHead;
cout<<"----"<<endl;
if(this->lenght > 0){
for(int i = 0;i < n;i++,p = p->pNext){
cout<<p->data<<endl;
}
}
cout<<"----"<<endl;
}
template <class T>
void Queue<T>::clear(){
Node<T> *p = this->pHead->pNext,*p1;
this->pHead = this->pRear;
for(int i = 1;i < this->lenght;i++){
p1 = p->pNext;
delete p;
p = p1;
}
this->lenght = 0;
}
int main(int argc, const char * argv[]) {
Queue<int> q;
int i;
for(i = 0;i < 20;i++){
q.shift(i);
}
q.show(20);
for(i = 0;i < 20;i++){
cout<<q.unshift()<<endl;
}
q.clear();
q.unshift();
for(i = 20;i > 0;i--){
q.shift(i);
}
q.show(25);
q.clear();
q.show(20);
return 0;
}