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

Java中如何实现一个栈的功能的函数?

发布时间:2023-06-17 22:29:18

栈是一种数据结构,它遵循"后进先出"(Last In First Out,LIFO)的原则。在Java中,我们可以使用数组或者链表等数据结构来实现栈的功能。

使用数组实现栈

定义一个数组来存储栈元素,同时记录栈顶元素的下标,栈顶指针始终指向栈顶元素。

public class ArrayStack {
    private int[] stack;
    private int top; // 栈顶指针

    public ArrayStack(int capacity) {
        stack = new int[capacity];
        top = -1; // 栈顶指针初始化为-1
    }

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

    public boolean isFull() {
        return top == stack.length - 1;
    }

    public void push(int data) {
        if (isFull()) {
            throw new RuntimeException("Stack is full!");
        }
        stack[++top] = data;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        return stack[top--];
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        return stack[top];
    }
}

使用链表实现栈

定义一个链表,但是只能在链表的头部插入删除元素,每次插入新元素时,将其插入链表头部,每次删除元素时,删除链表头部元素。

public class LinkedStack {
    private Node top; // 栈顶元素

    private class Node {
        int data;
        Node next;

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

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

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

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        int data = top.data;
        top = top.next;
        return data;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty!");
        }
        return top.data;
    }
}

总结

根据功能需求选择使用数组或链表来实现栈的功能。无论是基于数组还是链表来实现栈,都需要注意栈顶指针或栈顶元素的存储和处理,以保证栈的基本功能能够得到实现。同时,我们也需要注意栈的边界条件,例如栈是否为空或已经满了等情况。