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).
Update (2015-06-11):
The class name of the Java function had been updated to Mystack instead of Stack.
implementation:
Class Stack {
Public
Push element x onto stack.
void push (int x) {
Dq.push_back (x);
last = x;
}
Removes the element on top of the stack.
void Pop () {
if (empty ()) return;
Vector<int> VEC;
while (!empty ()) {
Vec.push_back (Dq.front ());
Dq.pop_front ();
}
for (int i = 0; i < vec.size ()-1; i++) {
Push (Vec[i]);
}
}
Get the top element.
int Top () {
return last;
}
Return whether the stack is empty.
bool Empty () {
return dq.size () = = 0;
}
Private
Deque<int> DQ;
int last;
};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode225--implement Stack using Queues