something wrong...

the problem says Show how to implement the main queue functions Enque() and Deque() using two stacks S1 & S2

You allowed only to call push () and pop() functions of the two stacks to implement Enque()and Deque() functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <stack>
using namespace std;

template<typename T>
class double_stack_queue
{
    stack<T> S1;
    stack<T> S2;
public:
	void enqueue(const T& in)
	{
	    S1.push(in);
	}

	T dequeue() //Does not works like standard queue
	{
		while(!S1.empty()) {
			S2.push(S1.top());
			S1.pop();
		}
		T temp = S2.top();
		S2.pop();
		while(!S2.empty()) {
			S1.push(S2.top());
			S2.pop();
		}
		return temp;
	}
};

int main()
{
	double_stack_queue<int> foo;
	foo.enqueue(5);
	foo.enqueue(7);
	foo.enqueue(10);

	cout << foo.dequeue();
}
The code works for me. What problem are you having?

If you're thinking "this is one backwards way to implement a queue and it seems horribly inefficient" then you're right :). It demonstrates that a queue can be created from a stack and that's great to show the theoretical versatility of a push-down automaton, but in practice, you'd never do it this way.

Yea, thank you for reply but i want to know if there is a better way .
If you're limited to a stack then that's the right way to do it.
Topic archived. No new replies allowed.