Leetcode 225. Implement stack using Queues (using queues to implement stacks)

Source: Internet
Author: User

Original title URL: https://leetcode.com/problems/implement-stack-using-queues/

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 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). Idea: When the stack is pressed, a temporary queue is used to store the elements of the last stack (so that the team is first out), then the contents of the previous queue are added to the temporary queue, and then the temporary queue is overwritten back to the queue that holds the stack data, and the order is reversed.

Source:

Class Mystack {
    private queue<integer> Queue = new linkedlist<integer> ();
    Private queue<integer> buf = new linkedlist<integer> ();
    Push element x onto stack.
    public void push (int x) {
        buf.add (x);
        while (!queue.isempty ()) Buf.add (Queue.remove ());
        queue<integer> temp = queue;
        queue = BUF;
        BUF = temp;
    }

    Removes the element on top of the stack.
    public void Pop () {
        queue.remove ();
    }

    Get the top element.
    public int Top () {
        return Queue.peek ();
    }

    Return whether the stack is empty.
    public Boolean empty () {
        return queue.isempty ();
    }
}
Time complexity: Stack o (n), stack, view stack top is O (1), Space complexity is O (n)





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.