I am trying to implement a Queue using 2 stacks in c++, this is what I did so fa
ID: 3642717 • Letter: I
Question
I am trying to implement a Queue using 2 stacks in c++, this is what I did so far and now I am stuck , I am not sure if I am in the right track.. Could you please help me finish this, thanks
#include <iostream>
using namespace std;
class Stack
{
public:
void stack_init(int size);
void push(int number);
int pop();
int top();
bool isEmpty( );
void enqueue(int value);
int dequeue( int value);
private:
int A [10];
int topOfStack;
int max_len;
};
Stack in;
Stack out;
void Stack::stack_init (int size)
{
max_len = size-1;
topOfStack= -1;
}
bool Stack::isEmpty()
{
return (topOfStack == -1);
}
int Stack:: pop()
{
if(!isEmpty())
return A[topOfStack--];
else
return NULL;
}
void Stack::push(int number)
{
if (topOfStack != max_len)
A[++topOfStack] = number;
}
int Stack::top()
{
return A[topOfStack];
}
void Stack:: enqueue(int value)
{
in.push(value);
}
int Stack:: dequeue(int value)
{
if(out.isEmpty())
{
while( ! in.isEmpty())
{
out.push(in.pop());
}
}
return out.pop();
}
int main()
{
Stack s;
s.enqueue(1);
s.enqueue(2);
s.enqueue(3);
s.enqueue(4);
return 0;
}
Explanation / Answer
#ifndef QUEUE_H #define QUEUE_H #include #include // This code brought to you by 10yo Talisker template class ts_queue { private: std::stack in; std::stack out; void turnover(); void turn_back_over(); void dump_stack(std::stack& stack); public: void push(T); void pop(); int size(); T& front(); T& back(); bool empty() const; void dump(); // dump output state, for debugging }; template void ts_queue::turnover() { // sample implementation, O(n) while (!in.empty()) { out.push(in.top()); in.pop(); } } template void ts_queue::turn_back_over() { // sample implementation, O(n) while (!out.empty()) { in.push(out.top()); out.pop(); } } template void ts_queue::push(T t) { in.push(t); } template void ts_queue::pop() { if (out.empty()) { turnover(); } out.pop(); } template int ts_queue::size() { return in.size() + out.size(); } template T& ts_queue::front() { if (out.empty()) { turnover(); } out.top(); } template T& ts_queue::back() { if (in.empty()) { turn_back_over(); } in.top(); } template bool ts_queue::empty() const { return in.empty() && out.empty(); } // A couple of debugging functions, non-standard template void ts_queue::dump_stack(std::stack& st) { using namespace std; stack temp; while (!st.empty()) { coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.