Skip to content

Instantly share code, notes, and snippets.

@miladabc
Created July 7, 2018 16:33
Show Gist options
  • Save miladabc/d9724ba4441004d97d802e19626928d7 to your computer and use it in GitHub Desktop.
Save miladabc/d9724ba4441004d97d802e19626928d7 to your computer and use it in GitHub Desktop.
Implementation of Queue with 2 array Stacks
//Milad Abbasi
//06-07-2018
//Implementation of Queue with 2 array Stacks
#include <iostream>
using namespace std;
#define MAX_SIZE 5
class Stack
{
int top, top2;
public:
int a[MAX_SIZE], b[MAX_SIZE];
Stack() { top = -1; top2 = -1; }
void push(int x);
void pop();
bool isEmpty();
int peek();
};
void Stack::push(int x)
{
if (top >= MAX_SIZE)
{
cout << "Stack Overflow";
return;
}
else
{
a[++top] = x;
return;
}
}
void Stack::pop()
{
if (top < 0)
{
cout << "Stack Underflow";
return;
}
else
{
while(top != -1)
b[++top2] = a[top--];
top2--;
while(top2 != -1)
a[++top] = b[top2--];
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
int Stack::peek()
{
if (top < 0)
{
cout << "Stack Underflow";
return -1;
}
else
{
int peek;
while(top != -1)
b[++top2] = a[top--];
peek = b[top2];
while(top2 != -1)
a[++top] = b[top2--];
return peek;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment