Leetcode 225: Implement Stack using Queues, leetcodequeues

Source: Internet
Author: User

Leetcode 225: Implement Stack using Queues, leetcodequeues
Implement Stack using QueuesTotal Accepted:3468Total Submissions:11988

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 useOnlyStandard operations of a queue -- which means onlypush to back,peek/pop from front,size, Andis emptyOperations are valid.
  • Depending on your language, queue may not be supported natively. you may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack ).

Update ):
The class name ofJavaFunction had been updatedMyStackInstead of Stack.

[Idea]

I didn't come up with a good solution. It was two queues that put all except the last one in another queue in turn.

[CODE]

class MyStack {    // Push element x onto stack.    Queue<Integer> q1 = new LinkedList<Integer>();    Queue<Integer> q2 = new LinkedList<Integer>();        public void push(int x) {        q1.offer(x);    }    // Removes the element on top of the stack.    public void pop() {        while(q1.size()>1) q2.offer(q1.poll());        q1.poll();        Queue<Integer> q = q1;        q1 = q2;        q2 = q;    }    // Get the top element.    public int top() {        while(q1.size()>1) q2.offer(q1.poll());        int x = q1.poll();        q2.offer(x);        Queue<Integer> q = q1;        q1 = q2;        q2 = q;        return x;    }    // Return whether the stack is empty.    public boolean empty() {        return q1.isEmpty();    }}



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.