Created
October 5, 2022 17:21
-
-
Save menangen/2f0dbb5684c974a0893d05dd6ee2102e to your computer and use it in GitHub Desktop.
Hello c++ Queue structure
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 <cassert> | |
#include <iostream> | |
#define STREAM std::ostream& | |
struct Player { | |
int score; | |
Player (int s) { this -> score = s; } | |
Player () { this -> score = 0; } | |
friend | |
STREAM operator << (STREAM os, const Player& p) { | |
os << "Player <" << p.score << ">\t"; | |
return os; | |
} | |
}; | |
/** Definition of the node */ | |
template <class Object> | |
struct node { | |
Object data; | |
node<Object> *next; | |
}; | |
/** Definition of the queue class */ | |
template <class Object> | |
class queue { | |
public: | |
/** Show queue */ | |
void display() { | |
node<Object> *current = queueFront; | |
if (current == NULL) std::cout << "\n\t! [EMPTY queue] !" << std::endl; | |
else { | |
std::cout << "Front --> "; | |
while (current != NULL) { | |
std::cout << current->data; | |
current = current->next; | |
} | |
std::cout << std::endl; | |
} | |
std::cout << "\tSize of queue: " << size << std::endl; | |
} | |
/** Default constructor*/ | |
queue() { | |
queueFront = NULL; | |
queueRear = NULL; | |
size = 0; | |
} | |
/** Destructor */ | |
~queue() {} | |
/** Determine whether the queue is empty */ | |
bool isEmptyQueue() { return (queueFront == NULL); } | |
/** Add new item to the queue */ | |
void enQueue(Object item) { | |
node<Object> *newNode; | |
newNode = new node<Object>; | |
newNode->data = item; | |
newNode->next = NULL; | |
if (queueFront == NULL) { | |
queueFront = newNode; | |
queueRear = newNode; | |
} else { | |
queueRear->next = newNode; | |
queueRear = queueRear->next; | |
} | |
size++; | |
} | |
/** Return the first element of the queue */ | |
Object front() { | |
assert(queueFront != NULL); | |
return queueFront->data; | |
} | |
/** Remove the top element of the queue */ | |
void deQueue() { | |
node<Object> *temp; | |
if (!isEmptyQueue()) { | |
temp = queueFront; | |
queueFront = queueFront->next; | |
delete temp; | |
size--; | |
} else { | |
std::cout << "Queue is empty !" << std::endl; | |
} | |
} | |
/** Clear queue */ | |
void clear() { queueFront = NULL; } | |
private: | |
node<Object> *queueFront; /**< Pointer to the front of the queue */ | |
node<Object> *queueRear; /**< Pointer to the rear of the queue */ | |
int size; | |
}; | |
int main() { | |
std::cout << "Hello, Queue!\n"; | |
auto n = queue<Player>(); | |
Player p = Player(12); | |
n.enQueue(p); | |
n.enQueue(Player(14)); | |
n.display(); | |
n.deQueue(); n.display(); | |
n.deQueue(); n.display(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment