Last active
February 15, 2017 14:10
-
-
Save Ionizing/c883c5acf529e7dd34c71107a8d7edda to your computer and use it in GitHub Desktop.
Queue template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#define MAXSIZE 20 | |
using namespace std; | |
template<typename Element> | |
class Queue | |
{ | |
private: | |
Element Data[MAXSIZE]; | |
int front = 0; | |
int back = 0; | |
public: | |
Queue() {} | |
~Queue() {} | |
bool IsEmpty() { return (back == front); } | |
//int Length() { return ((back - front + MAXSIZE) % MAXSIZE-1); }//修改后死循环 | |
int Length() { return (back - front + MAXSIZE) % MAXSIZE ; } | |
bool IsFull() { return Length() == MAXSIZE - 1; } | |
Element GetHead() { | |
if (IsEmpty()) { | |
cerr << "Queue EMPTY! Cannot GetHead()" << endl; | |
return (Element)false; | |
} | |
else { | |
return Data[front]; | |
} | |
} | |
bool EnQueue(const Element item) { | |
if (IsFull()) { | |
cerr << "Queue FULL! Cannot EnQueue()" << endl; | |
return false; | |
} | |
else { | |
//Data[(++back) % MAXSIZE] = item; | |
Data[(back++) % MAXSIZE] = item; | |
} | |
} | |
Element DeQueue() { | |
if (IsEmpty()) { | |
cerr << "Queue EMPTY! Cannot DeQueue()" << endl; | |
return (Element)false; | |
} | |
else { | |
auto tmpdata = Data[front]; | |
front = (front + 1) % MAXSIZE; | |
return tmpdata; | |
} | |
} | |
void QueueTraverse() { | |
if (IsEmpty()) { | |
cerr << "Queue Empty! Cannot Traverse!" << endl; | |
return; | |
} | |
else { | |
for (int i = front; (back - i + MAXSIZE) % MAXSIZE; i = (i + 1) % MAXSIZE) { | |
cout << Data[i] << " "; | |
} | |
} | |
} | |
}; | |
int main() | |
{ | |
Queue<int> Qtest; | |
for (int i = 0; i<MAXSIZE; i++) { | |
Qtest.EnQueue(i); | |
} | |
Qtest.QueueTraverse(); | |
while (!Qtest.IsEmpty()) { | |
cout << Qtest.DeQueue() << endl; | |
} | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment