Last active
August 29, 2015 14:03
-
-
Save ivycheung1208/40b53ce17164e2126777 to your computer and use it in GitHub Desktop.
CC150 3.5 Class Beta
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
/* 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