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).
This problem can run a few examples of their own first will find that there are rules to follow, the main idea is two stacks, a stack1 for push, and another stack2 for pop, the key is in the process from Stack1 to Stack2, or directly on the code bar, at a glance:
Class Myqueue { linkedlist<integer> stack1 = new linkedlist<integer> (); linkedlist<integer> Stack2 = new linkedlist<integer> (); Push element x to the back of the queue. public void push (int x) { stack1.push (x); } Removes the element from in front of the queue. public void POPs () { if (Stack2.isempty ()) { while (!stack1.isempty ()) { Stack2.push (Stack1.pop ()) };} } Stack2.pop (); } Get the front element. public int Peek () { if (Stack2.isempty ()) { while (!stack1.isempty ()) { Stack2.push (Stack1.pop ()); } } return Stack2.peek (); } Return whether the queue is empty. public Boolean empty () { return stack1.isempty () && stack2.isempty ();} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode-implement Queue using Stacks