题解 | #逆波兰表达式求值#

逆波兰表达式求值

http://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

import java.util.*;


public class Solution {
    
    static int operator(int n1, int n2, String op) {
        if (op.equals("+")) return n1 + n2;
        else if (op.equals("-")) return n1 - n2;
        else if (op.equals("*")) return n1 * n2;
        else if (op.equals("/")) return n1 / n2;
        else return -1;
    }
    
    static boolean isOperator(String op) {
        return op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/");
    }
    
    static int solve01(String[] tokens) {
        LinkedListStack<Integer> stack = new LinkedListStack<>();
        for (int i = 0 ; i < tokens.length; ++i) {
            if (isOperator(tokens[i])) {
                Integer num1 = stack.pop();
                Integer num2 = stack.pop();
                Integer res = operator(num2, num1, tokens[i]);
                stack.push(res);
            }
            else {
                stack.push(Integer.parseInt(tokens[i]));
            }
        }
        return stack.pop();
    }
    
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        return solve01(tokens);
    }
}


/////////////////////链表
/**
 * 栈的实现 -- 链表
 * 优点: 使用灵活方便, 只要有需要的时候才会申请空间
 * 缺点: 除了要存储元素外, 还需要额外存储指针(引用)信息
 * @param <T>
 */
class Node<T> {
    T data;
    Node<T> next;
}

class LinkedListStack<T> {
    private Node<T> pHead;

    public LinkedListStack() {
        pHead = new Node<T>();
        pHead.data = null;
        pHead.next = null;
    }

    public int size() {
        int size = 0;
        Node<T> cur = pHead.next;

        while (cur != null) {
            cur = cur.next;
            size++;
        }
        return size;
    }


    public T pop() {
        Node<T> popNode = pHead.next;
        if (popNode == null) return null;
        pHead.next = popNode.next;
        return popNode.data;
    }

    public T top() {
        Node<T> topNode = pHead.next;
        if (topNode == null) return null;
        return topNode.data;
    }

    public void push(T e) {
        Node<T> tlNode = new Node<>();
        tlNode.data = e;
        tlNode.next = pHead.next;
        pHead.next = tlNode;
    }

    public boolean isEmpty() {
        return pHead.next == null;
    }


}
/////////////////////链表

全部评论

相关推荐

06-27 15:15
长安大学 Java
哈哈哈,你是老六:这种就是培训机构骗钱的
点赞 评论 收藏
分享
05-03 12:45
西南大学 Java
nsnzkv:你这项目写的内容太多了,说实话都是在给自己挖坑,就算简历过了,后面面试也难受
简历被挂麻了,求建议
点赞 评论 收藏
分享
06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务