LeetCode -- Implement Queue using Stacks
Description:
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.
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is 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 ).
Ideas:
This article describes how to use two stacks to implement a queue, but is familiar with the stack itself.
1. Use two stacks s1 and s2
2. When pushing, directly enter s2
3. In pop mode, the s2 item is first popped up into s1, then one item is popped up from s1, and then the elements in S1.
4. peek, similar to pop, the difference is that only values are not deleted. Pop up each item in s2 into s1, n = s1.pop (), then the s1 elements one by one into s2, and return n.
5. empty: Check whether s2 is empty.
Implementation Code:
public class Queue { public Queue(){ _s1 = new Stack
(); _s2 = new Stack
(); } private Stack
_s1 ; private Stack
_s2; // Push element x to the back of queue. public void Push(int x) { _s2.Push(x); } // Removes the element from front of queue. public void Pop() { while(_s2.Count > 0){ _s1.Push(_s2.Pop()); } _s1.Pop(); while(_s1.Count > 0) { _s2.Push(_s1.Pop()); } } // Get the front element. public int Peek() {while(_s2.Count > 0){_s1.Push(_s2.Pop());} var n = _s1.Peek();while(_s1.Count > 0){_s2.Push(_s1.Pop());} return n; } // Return whether the queue is empty. public bool Empty() { return _s2.Count == 0; }}