代码随想录算法训练营第十天 | 232.用栈实现队列、232.用栈实现队列

文章讲述了如何使用栈和队列数据结构来实现先进先出(FIFO)和后入先出(LIFO)的数据结构,包括MyQueue类的实现方法,以及如何仅用两个队列实现一个后入先出栈MyStack的操作
摘要由CSDN通过智能技术生成

代码随想录算法训练营第十天 | 232.用栈实现队列、232.用栈实现队列


这个方面有些了解,基础知识要牢牢的掌握。
队列:先进先出。
栈:后进先出。

如果不太了解栈和队列的话可以先看这篇文章:代码随想录


232.用栈实现队列link

题目:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false。

视频推荐:link

思路:使用两个栈,一个栈用于入栈,另一个用于出栈。
请添加图片描述

class MyQueue {
    //使用两个栈实现先入先出队列
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }

    public void push(int x) {
        stackIn.push(x);
    }
    public int pop() {
        if (stackOut.isEmpty()) {
            while (!stackIn.isEmpty())
                stackOut.push(stackIn.pop());
        }
        return stackOut.pop();
    }

    public int peek() {
        //取出数据,但不移除
        if (stackOut.isEmpty()) {
            while (!stackIn.isEmpty())
                stackOut.push(stackIn.pop());
        }
        return stackOut.peek();
    }
    public boolean empty() {
        if (stackIn.isEmpty() && stackOut.isEmpty())
            return true;
        else
            return false;
    }
}

232.用栈实现队列link

题目:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

思路:一个队列作为主要队列,另一个作为临时队列,存放中间值。

class MyStack {
    //使用两个队列实现一个后入先出(LIFO)的栈
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        queue1.add(x);
    }

    public int pop() {
    	//queue1中只存留最后一个入队的数据
        while (queue1.size() > 1)
            queue2.add(queue1.poll());

        int topElement = queue1.poll();
        //交换队列
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
        //清空queue2
        queue2.clear();
        return topElement;
    }

    public int top() {
        while (queue1.size() > 1)
            queue2.add(queue1.poll());
        int topElement = queue1.peek();
        queue2.add(queue1.poll());//清空q1
        //交换队列
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
        queue2.clear();
        return topElement;
    }

    public boolean empty() {
        return queue1.isEmpty();
    }
}


感谢您的观看,谢谢!
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值