欢迎访问宙启技术站
智能推送

实现栈的功能:Java函数示例

发布时间:2023-06-27 05:09:29

1. 创建栈

创建栈需要定义一个类,并在类中定义栈的数组、栈的容量、栈的指针等属性。代码示例:

public class Stack {
    private int[] stack; // 定义栈的数组
    private int top; // 定义栈顶指针
    private int capacity; // 定义栈的容量
    public Stack(int size) { // 构造函数,初始化栈的大小
        stack = new int[size];
        top = -1;
        capacity = size;
    }
}

2. 入栈

入栈操作需要将元素添加到栈顶,首先判断是否栈满,如果栈满需要抛出异常,否则将元素添加到栈顶,并将栈顶指针加一。代码示例:

public void push(int x) throws Exception {
    if (top == capacity -1) {
        throw new Exception("栈已满!");
    }
    stack[++top] = x;
}

3. 出栈

出栈操作需要将栈顶元素弹出,并将栈顶指针减一,首先判断是否栈空,如果栈空需要抛出异常。代码示例:

public int pop() throws Exception {
    if (top == -1) {
        throw new Exception("栈已空!");
    }
    int x = stack[top--];
    return x;
}

4. 获取栈顶元素

获取栈顶元素操作需要返回栈顶元素,首先判断是否栈空,如果栈空需要抛出异常。代码示例:

public int peek() throws Exception {
    if (top == -1) {
        throw new Exception("栈已空!");
    }
    return stack[top];
}

5. 判断栈是否为空

判断栈是否为空操作需要判断栈顶指针是否为-1。代码示例:

public boolean isEmpty() {
    return top == -1;
}

6. 获取栈的大小

获取栈的大小操作需要返回栈顶指针加一。代码示例:

public int getSize() {
    return top + 1;
}

7. 使用栈实现逆波兰式求值

逆波兰式求值是一种后缀表达式,将运算符放在操作数后面。实现逆波兰式求值需要使用栈实现,首先将表达式拆分成操作数和操作符,然后按顺序进行计算,并将计算结果入栈,最终栈里只剩下一个元素,就是计算结果。代码示例:

public int evalRPN(String[] tokens) throws Exception {
    Stack<Integer> stack=new Stack<Integer>(tokens.length);
    for (int i = 0; i < tokens.length; i++) {
        String t = tokens[i];
        if (t.equals("+")) { // 加法
            int b = stack.pop();
            int a = stack.pop();
            stack.push(a + b);
        } else if (t.equals("-")) { // 减法
            int b = stack.pop();
            int a = stack.pop();
            stack.push(a - b);
        } else if (t.equals("*")) { // 乘法
            int b = stack.pop();
            int a = stack.pop();
            stack.push(a * b);
        } else if (t.equals("/")) { // 除法
            int b = stack.pop();
            int a = stack.pop();
            stack.push(a / b);
        } else { // 操作数
            stack.push(Integer.parseInt(t));
        }
    }
    return stack.pop();
}

以上是栈的常用操作和使用方法的Java函数示例。栈是一种常用的数据结构,可以用于解决很多实际问题,如括号匹配、后缀表达式求值等。熟练掌握栈的操作和使用方法,有助于提高编程能力和解决实际问题的能力。