Skip to content

Instantly share code, notes, and snippets.

@lablnet
Created March 28, 2021 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lablnet/02559ec8bc36dd02a55f209bd0e49c4e to your computer and use it in GitHub Desktop.
Save lablnet/02559ec8bc36dd02a55f209bd0e49c4e to your computer and use it in GitHub Desktop.
Stack and Queue implementation to array in C++
#include <iostream>
template <typename T>
class Stack {
public:
T *arr = new T[sizeof(T)];
int top = -1;
void push(T element)
{
this->top = this->top + 1;
this->arr[this->top] = element;
}
T pop()
{
if (this->isEmpty()) {
std::cout << "Stack underflow error" << std::endl;
return -1;
} else {
this->top = this->top - 1;
return this->arr[this->top + 1];
}
}
bool isEmpty()
{
if (this->top < 0)
return true;
else
return false;
}
void display()
{
for (int i = 0; i <= this->top; i++) {
std::cout << this->arr[i] << " ";
}
std::cout << std::endl;
}
void flush()
{
delete[] this->arr;
}
};
template <typename T>
class Queue {
public:
T arr[100];
int head = -1;
int tail = -1;
void enQueue(T elem)
{
if (this->head == -1) {
this->head = 0;
}
this->tail = this->tail + 1;
this->arr[this->tail] = elem;
}
T deQueue()
{
if (this->isEmpty()) {
std::cout << "Queue is empty" << std::endl;
return -1;
}
T element = this->arr[this->head];
if (this->head >= this->tail) {
this->head = -1;
this->tail = -1;
} else
this->head = this->head + 1;
return element;
}
bool isEmpty() {
if (this->head == -1)
return true;
else
return false;
}
void display()
{
for (int i = this->head; i <= this->tail; i++) {
std::cout << this->arr[i] << " ";
}
std::cout << std::endl;
}
};
int main() {
std::cout << "STACK" << std::endl;
Stack<int> s = Stack<int>();
for (int i = 0; i <= 10; i++) {
s.push(i);
}
std::cout << "Displaying elements: " << std::endl;
s.display();
std::cout << std::endl;
std::cout << "POP: " << s.pop() << std::endl;
std::cout << "Displaying elements: " << std::endl;
s.display();
std::cout << std::endl;
std::cout << "QUEUE" << std::endl;
Queue<int> q = Queue<int>();
for (int i = 0; i <= 10; i++) {
q.enQueue(i);
}
std::cout << "Displaying elements: " << std::endl;
q.display();
std::cout << std::endl;
std::cout << "POP: " << q.deQueue() << std::endl;
std::cout << "Displaying elements: " << std::endl;
q.display();
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment