Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- Push (x)--push element x to the back of the queue.
- Pop ()--Removes the element from in front of the queue.
- Peek ()--Get the front element.
- Empty ()--Return whether the queue is empty.
Notes:
- you must Use only standard operations of a stack--which means only < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:12.6000003814697px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">push to top ,
peek/pop from top
, size
, And is empty
operations is valid.
- Depending on your language, stack may is not supported natively. You could simulate a stack by using a list or deque (double-ended queue), as long as if you have standard operations of a s Tack.
- You may assume this all operations is valid (for example, no pop or peek operations would be called on an empty queue).
Implement queues with stacks.
Two stacks to implement a queue.
Class Queue {public: stack<int>s1,s2; Push element x to the back of the queue. void push (int x) { s1.push (x); } Removes the element from in front of the queue. void pop (void) { while (!s1.empty ()) { S2.push (s1.top ()); S1.pop (); } S2.pop (); while (!s2.empty ()) { S1.push (s2.top ()); S2.pop (); } } Get the front element. int peek (void) { while (!s1.empty ()) { S2.push (s1.top ()); S1.pop (); } int x = S2.top ();//Fetch stack top element while (!s2.empty ()) { S1.push (s2.top ()); S2.pop (); } return x; } Return whether the queue is empty. bool Empty (void) { return s1.empty (); }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode-232-implement Queue using Stacks