day10 算法打卡| 栈与队列|Leetcode232用栈实现队列、225用栈实现队列 | 理解队列与栈的不同

Leetcode232:用栈实现队列

题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/description/

思路:用两个栈实现队列操作

day10 算法打卡| 栈与队列|Leetcode232用栈实现队列、225用栈实现队列 | 理解队列与栈的不同_第1张图片

Java实现代码:(栈可以使用Stack或Deque实现)

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

//leetcode submit region begin(Prohibit modification and deletion)
class MyQueue {
    //使用stack可以
    private Deque inStack;
    private Deque outStack;

    public MyQueue() {
        inStack = new ArrayDeque<>();
        outStack = new ArrayDeque<>();
    }
    
    public void push(int x) {
        inStack.push(x);
    }
    
    public int pop() {
        if(outStack.isEmpty()){
            while (!inStack.isEmpty()){
                outStack.push(inStack.pop());
            }
        }
        int popnum = outStack.pop();
        return popnum;
    }
    
    public int peek() {
        int peeknum = pop();
        outStack.push(peeknum);
        return peeknum;
    }
    
    public boolean empty() {
        if(outStack.isEmpty()&& inStack.isEmpty()){
            return true;
        }
        return false;
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
//leetcode submit region end(Prohibit modification and deletion)

Leetcode225:用栈实现队列

(队列可以使用Queue或Deque实现)

题目链接:https://leetcode.cn/problems/implement-stack-using-queues/description/

可以使用两个队列实现,也可以使用一个队列实现如下:

使用一个队列Queue实现的Java代码:

import java.util.LinkedList;
import java.util.Queue;

//leetcode submit region begin(Prohibit modification and deletion)
class MyStack {
    private Queue thequeue;

    public MyStack() {
        thequeue = new LinkedList<>();
    }
    
    public void push(int x) {
        thequeue.add(x);
    }
    public int pop() {
        int size = thequeue.size();
        for(int i =0;i

使用两个队列Queue实现的Java代码:(两个队列实现的方法有很多,这是其中一种)

import java.util.LinkedList;
import java.util.Queue;

//leetcode submit region begin(Prohibit modification and deletion)
class MyStack {
    private Queue thequeue1;
    private Queue thequeue2;

    public MyStack() {
        thequeue1 = new LinkedList<>();
        thequeue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        if(thequeue1.isEmpty()){
            thequeue2.add(x);
        }else {
            thequeue1.add(x);
        }
    }
    public int pop() {
        Queue pushqueue = new LinkedList<>();
        Queue popqueue = new LinkedList<>();
        if(thequeue1.isEmpty()){
            pushqueue = thequeue1;
            popqueue = thequeue2;
        }else {
            pushqueue = thequeue2;
            popqueue = thequeue1;
        }
        //从pop中输出放入push (出pop.size-1个)
        int size = popqueue.size();
        for(int i=0;i

你可能感兴趣的:(开发语言,java,leetcode,算法)