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

在Java函数中实现栈的基本操作

发布时间:2023-07-02 18:28:08

栈是一种常见的数据结构,它遵循后进先出(Last-In-First-Out,LIFO)的原则。在Java中,我们可以使用数组或链表来实现栈的基本操作,包括入栈(push)、出栈(pop)、查看栈顶元素(peek)和判断栈是否为空(isEmpty)。

使用数组实现栈的基本操作的代码如下:

public class ArrayStack {
    private int maxSize; // 栈的最大容量
    private int top; // 栈顶元素的索引
    private int[] stack; // 存储元素的数组

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.top = -1;
        stack = new int[maxSize];
    }

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

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

    public void push(int value) {
        if (isFull()) {
            System.out.println("栈已满,无法入栈");
            return;
        }

        stack[++top] = value;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空,无法出栈");
        }

        return stack[top--];
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }

        return stack[top];
    }
}

使用链表实现栈的基本操作的代码如下:

public class LinkedStack {
    private Node top; // 栈顶节点

    public boolean isEmpty() {
        return top == null;
    }

    public void push(int value) {
        Node node = new Node(value);
        node.next = top;
        top = node;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空,无法出栈");
        }

        int value = top.value;
        top = top.next;
        return value;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }

        return top.value;
    }

    private class Node {
        private int value;
        private Node next;

        public Node(int value) {
            this.value = value;
        }
    }
}

以上代码分别实现了使用数组和链表来实现栈的基本操作。使用时,可以根据需要选择合适的实现方式。