could anyone describe to me how to implement a stack using two queues. just cant get my head round it.thanks to anyone who helps.

Recommended Answers

All 2 Replies

It takes about five minutes to figure out. Just take a few coins and use queue-like operations to simulate the pushing and popping of a stack. The nice thing about stacks and queues is that the concepts are so simple you can easily diagram them with minimal effort.

Use two stacks. Lets name that as addStack and removeStack. Call addStack.push() method in enequeue() and in dequeue(), check whether removeStack is empty. If it is empty, copy the elements off addStack in reverse order to removeStack and flush addStack(). So now in dequeue() invoke, removeStack.pop(). Simple.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.