232. Implement Queue using Stacks
Total Accepted: 27024 Total Submissions: 79793 Difficulty: Easy
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
class Queue {public: // Push element x to the back of queue. void push(int x) { instk.push(x); } // Removes the element from in front of queue. void pop(void) { if(outstk.empty()){ while(!instk.empty()){ outstk.push(instk.top()); instk.pop(); } } outstk.pop(); } // Get the front element. int peek(void) { if(outstk.empty()){ while(!instk.empty()){ outstk.push(instk.top()); instk.pop(); } } return outstk.top(); } // Return whether the queue is empty. bool empty(void) { return instk.empty() && outstk.empty(); }private: stack instk; stack outstk;};
225. Implement Stack using Queues
Total Accepted: 25628 Total Submissions: 84579 Difficulty: Easy
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
class Stack {public: // Push element x onto stack. void push(int x) { if(que1.empty()){ que2.push(x); }else{ que1.push(x); } } // Removes the element on top of the stack. void pop() { if(que1.empty()){ while(que2.size() != 1){ que1.push(que2.front()); que2.pop(); } que2.pop(); }else{ while(que1.size() != 1){ que2.push(que1.front()); que1.pop(); } que1.pop(); } } // Get the top element. int top() { int x = 0; if(que1.empty()){ while(!que2.empty()){ x = que2.front(); que2.pop(); que1.push(x); } }else{ while(!que1.empty()){ x = que1.front(); que1.pop(); que2.push(x); } } return x; } // Return whether the stack is empty. bool empty() { return que1.empty() && que2.empty(); }private: queue que1; queue que2;};