剑指总结--栈与队列

1. 用两个栈实现队列

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

   int pop() {
        int a;
        if(stack2.empty()){
            while(!stack1.empty()){
                a=stack1.top();
                stack2.push(a);
                stack1.pop();
            }
        }
        a=stack2.top();
        stack2.pop();
        return a;
         
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

2. 用队列实现栈

思路:同样是两个队列实现栈的push和pop操作。分为数据队列和辅助队列,基本没有什么难点,正常往数据队列push,pop时,将数据队列的数据移到辅助队列,直至剩下最后一个队列尾元素,POP出,并将辅助队列在push回数据队列中


package com.sxt.test.java;
 
public class Queue2Stack {
    /**
     * 用队列的入队和出队
     * 来实现栈的入栈和出栈
     * */
    
    Queue queue1 = new Queue();//主要存放数据
    Queue queue2 = new Queue();//辅助
    
    public void push(Object o) {
        queue1.add(o);
    }
    
    public Object pop() {
        Object o = null;
        while(queue1.length()>1) {
            queue2.add(queue1.poll());
        }
        if(queue1.length()==1) {
            o = queue1.poll();
            while(queue2.length()>0) {
                queue1.add(queue2.poll());
            }
        }
        
        return o;
    }
    
    public int length() {
        return queue1.length();
    }
    }

3. 包含min函数的栈

import java.util.Stack;

public class Solution {

    Stack<Integer> stack = new Stack();
    int min = 9999;
    public void push(int node) {
        if(node<min)
        {
            stack.push(min);
            min = node;
        }
        stack.push(node);
    }
    
    public void pop() {
        if(stack.peek() == min)
        {
            stack.pop();
            min = stack.peek();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return min;
    }
}

4. 判断栈的压入、弹出序列是否正确

算法思想:就是将自己判断栈的弹出序列是否合法的

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      if(pushA.length == 0 || popA.length == 0)
        {
            return false;
        }
        Stack<Integer> stack = new Stack<Integer>();
        int index = 0;
        int len = pushA.length;
        for(int i = 0;i<len;++i)
        {
            stack.push(pushA[i]);
            while(!stack.isEmpty() && stack.peek() == popA[index])
            {
                stack.pop();
                ++index;
            }
        }
        return stack.isEmpty();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值