01 零基础学算法(栈、队列和堆)

本文介绍了如何使用两个队列实现栈、两个栈实现队列,以及最小值栈的实现。此外,讲解了栈的弹出序列合法性判断、栈在计算器中的应用以及如何用堆找到最小的K个数。通过实例解析,帮助初学者理解这些基本数据结构的操作和用途。
摘要由CSDN通过智能技术生成

1 栈、队列和堆

1.1 两个队列实现栈

栈:1 2 3 4 5  出栈顺序 5 4 3 2 1, 相应的队列(先进先出)应该为 5 4 3 2 1。

通过两个队列来实现栈:

假设队列1已经有了 1 2 3 4,这是来了个5。我们让5进入队列2,然后把队列1(4,3,2,1)中的数据赋值给队列2,此时,队列2为 5 4 3 2 1。最后,我们把队列2中的数据赋值给队列1,队列1中的数据为5 4 3 2 1.  

/**
 * 通过临时队列来实现栈
 */
class MyStack {

    Queue<Integer> dataQueue;
    Queue<Integer>  tempQueue;
    /** Initialize your data structure here. */
    public MyStack() {
        dataQueue = new LinkedList<Integer>();
        tempQueue = new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        tempQueue.add(x);
        while(!dataQueue.isEmpty()){
           tempQueue.offer(dataQueue.poll());
        }
        while(!tempQueue.isEmpty()){
           dataQueue.offer(tempQueue.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return dataQueue.poll();

    }
    
    /** Get the top element. */
    public int top() {
        return dataQueue.peek();

    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
       if(dataQueue.isEmpty()){
          return true;
       }
       return false;
    }
}

1.2 两个栈实现队列

和1.1的原理类似。

class CQueue {

    Stack tempStack;
    Stack dataStack;
    public CQueue() {
        tempStack = new Stack<Integer>();
        dataStack = new Stack<Integer>();
    }
    
    public void appendTail(int value) {
    
        while(!dataStack.isEmpty()){
            tempStack.push(dataStack.po
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值