Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Last active August 29, 2015 14:03
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 ivycheung1208/40b53ce17164e2126777 to your computer and use it in GitHub Desktop.
Save ivycheung1208/40b53ce17164e2126777 to your computer and use it in GitHub Desktop.
CC150 3.5 Class Beta
/* CC150 3.5
* Implement a MyQueue class which implements a queue using two stacks.
*/
#ifndef MYQUEUEBETA_H
#define MYQUEUEBETA_H
#include <iostream>
#include <stack>
using namespace std;
class MyQueue{
public: // Only keep track of the oldest element since it's a queue!
int front(); // returns the next element in the queue
void enqueue(int data); // inserts a new element at the end of the queue
int dequeue(); // removes the next element in the queue and returns the new next element
private:
stack<int> stackIn;
stack<int> stackOut;
void stackShift();
};
int MyQueue::front()
{
stackShift();
if (!stackOut.empty())
return stackOut.top();
else
return -1;
}
void MyQueue::enqueue(int data)
{
stackIn.push(data); // push data
return;
}
int MyQueue::dequeue()
{
stackShift();
if (stackOut.empty())
return -1;
int data = stackOut.top(); // pop data
stackOut.pop();
return data;
}
void MyQueue::stackShift()
{
if (stackOut.empty()) {
while (!stackIn.empty()) {
stackOut.push(stackIn.top());
stackIn.pop();
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment