Moment For Technology

225. Implement stacks with queues

Posted on Aug. 8, 2022, 6:12 p.m. by Beth Tyler
Category: reading Tag: algorithm

class MyStack {
    QueueInteger queue = new LinkedList();
    QueueInteger helper = new LinkedList();

    public MyStack(a) {}public void push(int x) {
        queue.offer(x);
    }
    
    public int pop(a) {
        int tmp = 0;
        while (queue.size()  1) {
            tmp = queue.poll();
            helper.offer(tmp);
        }
        // The element to pop on the stack, the end of the queue, is no longer put in the helper queue, only poll
        tmp = queue.poll();
        // The helper goes to queue
        while(! helper.isEmpty()) { queue.offer(helper.poll()); }return tmp;
    }
    
    public int top(a) {
        int tmp = 0;
        while(! queue.isEmpty()) { tmp = queue.poll(); helper.offer(tmp); }// The helper goes to queue
        while(! helper.isEmpty()) { queue.offer(helper.poll()); }return tmp;
    }
    
    public boolean empty(a) {
        returnqueue.isEmpty(); }}Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.