Leetcode225--implement Stack using Queues

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.