今天有两道算法题关于入栈、出栈操作

一、用两个栈来实现一个队列,完成队列的push和pop操作,队列中的元素为int类型

思路:两个栈实现队列,根据栈先进后出的原则,为了保证队列输出的顺序,必须进行两次入栈的操作。

两种解法大致相同。。。。

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(new Integer(node));//全部放入栈1之中
    }
    
    public int pop() {
        int pop;
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());//将栈1压到栈二当中
        }
        pop=stack2.pop().intValue();//将栈二的数据全部出栈
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());//将栈2压到栈1当中
        }
        return pop;
    }
}
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);//全部放入栈1之中
    }
    
    public int pop() {
       if(stack2.isEmpty())
       {
             while(!stack1.isEmpty())
             {
                stack2.push(stack1.pop());
            }
       }
      
        return stack2.pop();
    }
}

二、逆波兰数:用逆波兰表示法计算算术表达式的值。有效的运算符+,-,*,/。每个操作数可以是一个整数或另一个表达式。

Evaluate the value of an arithmetic expression in Reverse Polish Notation.Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

思路:也是借助于入栈出栈的想法,原始数据不停入栈。遇到运算符,两个数据出栈,先出栈的在右边,后出栈的在左边。再将运算结果入栈,直至遍历完所有的数字,直接进行出栈操作,得到最终结果。

import java.util.Stack;

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<Integer>();
        int a;
        int b;
        int i=0;
        for(;i<tokens.length;i++){
            String c=tokens[i];
            if(c.equals("+")){
                a=stack.pop();
                b=stack.pop();
                stack.add(b+a);
            }
            else if(c.equals("-")){
                a=stack.pop();
                b=stack.pop();
                stack.add(b-a);
            }
            else if(c.equals("*")){
                a=stack.pop();
                b=stack.pop();
                stack.add(b*a);
            }
            else if(c.equals("/")){
                a=stack.pop();
                b=stack.pop();
                stack.add(b/a);
            }
            
        }
        return stack.pop();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值