代码随想录算法训练营第9天 | (Stack, Queue) LeetCode 232, 225

本文介绍了如何使用栈(LIFO)和队列(FIFO)数据结构实现各自的功能,包括队列的offer(),poll(),peek()和栈的push(),pop(),top()等操作。作者提供了Java代码示例,展示了如何用两个栈实现一个队列,以及用两个队列实现一个栈。
摘要由CSDN通过智能技术生成

Queue

A queue supports the insert and remove operations using a first-in-first-out (FIFO) discipline.

offer(): insert an element in the tail of the queue.

poll(): get an element from the head of the queue. (remove from the queue)

peek(): read the value of a head element of the queue.

size(): how many elements are in the queue.

isEmpty(): if this queue is empty.

no pop, no push!

 Queue<Integer> queue = new LinkedList<>();

Stack

A stack is a collection that is based on the last-in-first-out (LIFO) policy.

push(element): push an element onto the stack

pop(don’t write anything): return and remove the item that was on the top of the stack

peak(): read the top element (tail)

poll() : get an element from the top (tail) (remove it from the stack)

offerFirst(): insert an element in the top of the stack. (tail) vs queue offer()

pollFirst(): get an element from the top of stack.

peekFirst(): read the value of top element in stack. (tail)

size(): how many elements are in the stack.

isEmpty(): if this stack is empty or the size of this stack is 0.

Different between stack.poll() vs stack. pop()?

So poll() returns null if the list is empty, and pop() (and removeFirst() ) raises a NoSuchElementException

Stack<Integer> stack = new LinkedList<>();

232. Implement Queue using Stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (pushpeekpop, and empty).

1. all elements go to stackIn when we push any new element

2. if there is any element in stackOut, the first element to get out of the queue would be stackOut.pop()

if there is no element in stackOut, we will add elements from stackIn to stackOut, then we can pop the first element in stackOut

we don't need to add elements back because the next one to pop out would be the one in the stackOut if stackOut is not empty.

class MyQueue {
// two variables declared
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    public MyQueue() {
// Constructor - Initializes the two stacks when an instance of MyQueue is created
//This ensures that when you create an instance of MyQueue, you have two empty stacks ready for use.
        stackIn = new Stack<>();
        stackOut = new Stack<>();    
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        shuffle();
        return stackOut.pop();
    }
    
    public int peek() {
        shuffle();
        return stackOut.peek();
    }
    
    public boolean empty() {
        if (stackOut.empty() && stackIn.empty()) {
            return true;
        } else {
            return false;
        }
    }

    public void shuffle() {
        // means we can directly peek or pop for queue
        if (!stackOut.empty()) {
            return;
        }
        // we need to dump elements from stackIn to get the first element
        while (!stackIn.empty()) {
            stackOut.push(stackIn.pop());
        }
    }
}
225. Implement Stack using Queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (pushtoppop, and empty).

Different from the above question, the other queue in this question is used to store elements.

Everytime we get the top element, we need to offer the elements back to q1

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
        // be careful
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();        
    }
    
    public void push(int x) {
        // offer() not push() 
        queue1.offer(x);
    }
    
    public int pop() {
        int temp = 0;
        while (!queue1.isEmpty()) {
            // poll() not pop()
            temp = queue1.poll();
            if (queue1.isEmpty()) {
                dumpToQueue1();
                break;
            } else {
                queue2.offer(temp);
            }    
        }
        return temp;  
    }
    
    public int top() {
        int temp = 0;
        while (!queue1.isEmpty()) {
            temp = queue1.poll();
            if (queue1.isEmpty()) {
                queue2.offer(temp);
                dumpToQueue1();
                break;
            } else {
                queue2.offer(temp);
            }      
        }
        return temp;  
    }
    
    public boolean empty() {
        if (queue1.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    public void dumpToQueue1() {
        while (!queue2.isEmpty()) {
            queue1.offer(queue2.poll());
        }
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值