力扣232题、225题(栈实现队列,队列实现栈)

栈与队列基础:

https://blog.csdn.net/m0_51167384/article/details/114456556?spm=1001.2101.3001.6650.8&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-8.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-8.no_search_link&utm_relevant_index=12

232、栈实现队列

具体实现:

使用栈来模式队列的行为,需要两个栈一个输入栈,一个输出栈,要注意输入栈和输出栈的关系。

在push数据的时候,只要数据放进输入栈就好

在pop的时候,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。

如果进栈和出栈都为空的话,说明模拟的队列为空了。

 

 

代码:

class MyQueue {
    Stack<Integer> stackOut;
    Stack<Integer> stackIn;
    public MyQueue() {
        stackOut = new Stack<>();//负责出栈
        stackIn = new Stack<>();//负责进栈
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        dumpStackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpStackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }

    private void dumpStackIn(){
        if (stackOut.isEmpty()){
            while (!stackIn.isEmpty()){
                stackOut.push(stackIn.pop());
            }
        }
    }
}

 

225、队列实现栈

具体实现:

用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,

queue1中的元素和栈中的保持一致

 

 

 

 

 

 代码:

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue2.offer(x);
        while(!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        Queue<Integer> queueTmp;
        queueTmp = queue1;
        queue1 = queue2;
        queue2 = queueTmp;
    }
    
    public int pop() {
        return queue1.poll();
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {
        return queue1.isEmpty();
    }
}

 

posted @ 2021-11-02 22:31  最近饭吃的很多  阅读(50)  评论(0)    收藏  举报