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

Java函数实现栈的基本操作(入栈、出栈、取栈顶元素)

发布时间:2023-07-02 02:18:09

在Java中,可以使用数组或链表来实现栈的基本操作。下面是使用数组方法实现的栈:

public class MyStack {

    private int[] stack;
    private int top;
    private int maxSize;

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

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

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

    public void push(int value) {
        if (isFull()) {
            System.out.println("Stack is full, cannot push element.");
            return;
        }
        stack[++top] = value;
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack is empty, cannot pop element.");
            return -1; // or throw an exception
        }
        return stack[top--];
    }

    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty, no element to peek.");
            return -1; // or throw an exception
        }
        return stack[top];
    }
}

使用链表方法实现栈的代码如下:

public class MyStack {

    private static class Node {
        private int data;
        private Node next;

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

    private Node top;

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

    public void push(int value) {
        Node newNode = new Node(value);
        if (isEmpty()) {
            top = newNode;
        } else {
            newNode.next = top;
            top = newNode;
        }
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack is empty, cannot pop element.");
            return -1; // or throw an exception
        }
        int data = top.data;
        top = top.next;
        return data;
    }

    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty, no element to peek.");
            return -1; // or throw an exception
        }
        return top.data;
    }
}

这些代码演示了栈的基本操作,包括入栈(push)、出栈(pop)和取栈顶元素(peek)。入栈操作会将一个元素添加到栈的顶部,出栈操作会删除栈顶的元素并返回其值,取栈顶元素操作则只返回栈顶的元素值而不删除它。

使用示例:

MyStack stack = new MyStack(5);

System.out.println(stack.isEmpty()); // Output: true

stack.push(1);
stack.push(2);
stack.push(3);

System.out.println(stack.peek()); // Output: 3

System.out.println(stack.pop()); // Output: 3

System.out.println(stack.peek()); // Output: 2

上述示例展示了栈的基本操作,并验证了实现的正确性。