Describe:
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).
Ideas:
1. Use the stack to implement a queue, that is, with a last-in-first-out stack to achieve FIFO-first queue
2. This is still difficult to think about, but it is better than to use the queue to implement the stack is easy to think, probably with two stacks of stack1 and Stack2 to simulate the queue
3. All elements are stack1 from the stack, all elements are stack2 out of the stack, and when the Stack2 is empty, all elements in the stack1 are pushed out of the stack and pushed all the way to Stack2, and then the stack is removed from the Stack2
4. Since the stack is last-in-first-out, two LIFO operations enable the function of the queue
Code:
Class Myqueue { stack<integer>stack1=new stack<integer> (); Stack<integer>stack2=new stack<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 Pop () { if (!stack2.empty ()) stack2.pop (); else {while (!stack1.empty ()) {Stack2.push (Stack1.pop ());} Stack2.pop ();} } Get the front element. public int Peek () { int num=0; if (!stack2.empty ()) num= Stack2.peek (); else {while (!stack1.empty ()) {Stack2.push (Stack1.pop ());} Num= Stack2.peek ();} return num; } Return whether the queue is empty. public Boolean empty () { if (Stack1.empty () &&stack2.empty ()) return true; return false; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode_implement Queue using Stacks