Leetcode Implement stack using queues (stack implemented 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 are must use only standard operations of a queue--which means only push to back, peek/pop from front, size, and are empty Operations are valid. Depending on your language, the queue may isn't be supported natively. You could simulate a queue by using a list or deque (double-ended queue) as long as your use only standard operations of a Q Ueue. You may assume this all operations are valid (for example, no POPs or top operations would be called on a empty stack).

The main idea: the use of queues to achieve the stack of push, pop, top and empty operations.

Solution: Each push operation, the element is placed at the head of the team, the other elements in order to move to the end of the team. The other operations are basically consistent with the queue operations in C++stl.

The code is as follows:

Class Mystack {public
:
    /** Initialize your data structure here. */
    Mystack () {While
        (Que.size ()) Que.pop ();
    }
    
    /** Push element x onto stack. */
    void push (int x) {
        que.push (x);
        int sz = Que.size ();
        while (Sz > 1) {
            Que.push (Que.front ());
            Que.pop ();
            sz--
        }
    }
    
    /** removes the element on top of the stack and returns that element. */
    int pop () {
        int tmp = Que.front ();
        Que.pop ();
        return tmp;
    }
    
    /** get the top element. */
    int Top () {return
        que.front ();
    }
    
    /** Returns Whether the stack is empty. * *
    bool Empty () {return
        que.empty ();
    }
Private:
    queue<int> que;

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.