Topic:
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.
Notes:
- you must Use only standard operations of a queue--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 Back ,
peek/pop from front , size , And is empty operations is valid.
- Depending on your language, queue May is not supported natively. You could simulate a queue by using a list or deque (double-ended queue), as long as if you have standard operations of a Q Ueue.
- You may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
Answer:
Using the queue to implement the stack, the queue is FIFO, the stack is advanced, so each queue element into the time, we put all the elements behind this element of the queue back into the queue, so that the last element into the queue can be the first queue
Code:
Class Mystack { queue<integer> queue=new linkedlist<integer> (); public void push (int x) { queue.offer (x); int I=queue.size ()-1; while (i>0) { queue.offer (Queue.poll ()); i--; } } public void Pop () { queue.poll (); } public int Top () { return Queue.peek (); } public Boolean empty () { return queue.isempty (); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode225 Implemet Stack using Queues java