Java数据结构-栈

栈是一个运算受限的先进后出的线性表。仅限在表的一端进行运算操作操作

代码实现

接口

java 复制代码
public interface Stack<E> {

    /**
     * 进栈
     *
     * @param e 元素
     * @throws NullPointerException 不允许空元素
     */
    void push(E e);

    /**
     * 退栈
     *
     * @return 返回弹出元素
     * @throws java.util.NoSuchElementException 没有元素错误
     */
    E pop();

    /**
     * 取栈顶
     *
     * @return 返回栈顶元素
     * @throws java.util.NoSuchElementException 没有元素错误
     */
    E getTop();

    /**
     * 是否空栈
     *
     * @return 返回结果
     */
    boolean isEmpty();

    /**
     * 检查元素是否为空指针
     * @param e 元素
     */
    default void check(E e) {
        if (e == null) {
            throw new NullPointerException();
        }
    }
}

顺序表实现

java 复制代码
public class StackSequence<E> implements Stack<E> {

    private Object[] elementData;

    /**
     * 游标
     */
    private int top;

    public StackSequence(int initialCapacity) {
        this.top = -1;
        if (initialCapacity <= 0) {
            elementData = new Object[10];
            return;
        }
        elementData = new Object[initialCapacity];
    }

    @Override
    public void push(E e) {
        check(e);
        ++top;
        if (top == elementData.length) {
            grow();
        }
        elementData[top] = e;
    }

    private void grow() {
        // 当前值的1.5倍
        elementData = Arrays.copyOf(elementData, (elementData.length + 1) / 2 * 3);
    }

    @Override
    @SuppressWarnings("unchecked")
    public E pop() {
        if (top < 0) {
            throw new NoSuchElementException();
        }
        Object elementDatum = elementData[top];
        elementData[top] = null;
        top--;
        return (E) elementDatum;
    }

    @Override
    @SuppressWarnings("unchecked")
    public E getTop() {
        if (top < 0) {
            throw new NoSuchElementException();
        }
        return (E) elementData[top];
    }

    @Override
    public boolean isEmpty() {
        return top < 0;
    }

    public int size() {
        return elementData.length;
    }
}

栈链表实现

java 复制代码
public class QueueLink<E> implements Queue<E> {

    protected Node<E> head;
    protected Node<E> rear;

    public QueueLink() {
        this.rear = new Node<>(null, null);
        this.head = new Node<>(null, this.rear);
    }

    @Override
    public void enqueue(E e) {
        check(e);
        rear.element = e;
        Node<E> node = new Node<>(null, null);
        rear.next = node;
        rear = node;
    }

    @Override
    public E dequeue() {
        Node<E> next = head.next;
        check(next.element);
        head.next = next.next;
        return next.element;
    }

    @Override
    public boolean isEmpty() {
        return head.next.element == null;
    }

    @Override
    public E getHead() {
        E element = head.next.element;
        check(element);
        return element;
    }

    protected static class Node<E> {
        private E element;
        private Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }

        public E getElement() {
            return element;
        }

        public void setElement(E element) {
            this.element = element;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }
    }
}

代码测试

Java 复制代码
/**
 * @author DawnStar
 * @since 2025/8/2
 */
public class StackTest {
    public static void main(String[] args) {

        // 顺序表实现
        StackSequence<String> stack = new StackSequence<>(3);
        System.out.print("栈顺序表:");
        stack.push("A");
        System.out.print(stack.pop());
        stack.push("B");
        stack.push("C");
        System.out.print(" " + stack.pop());
        stack.push("D");
        stack.push("E");
        System.out.print("、" + stack.pop());
        System.out.print("、" + stack.pop());
        System.out.print("、" + stack.pop() + "\n");
        System.out.println("栈顺序表大小:" + stack.size());


        Stack<String> linkStack = new StackLink<>();
        List<String> elements = List.of("A", "B", "C", "D", "E");
        System.out.println("栈链表进栈:" + String.join("、", elements));
        for (String element : elements) {
            linkStack.push(element);
        }
        System.out.print("出栈顺序:");
        while (!linkStack.isEmpty()) {
            System.out.print(" " + linkStack.pop());
        }
    }
}
相关推荐
狂团商城小师妹1 小时前
JAVA露营基地预约户外露营预约下单系统小程序
java·开发语言·微信小程序·小程序
yujkss2 小时前
23种设计模式之【状态机模式】-核心原理与 Java实践
java·ui·设计模式
钮钴禄·爱因斯晨2 小时前
数据结构|图论:从数据结构到工程实践的核心引擎
c语言·数据结构·图论
无名指的等待7123 小时前
Redisson的Lock和TryLock的区别
java·开发语言·数据库
new_daimond3 小时前
Apache Shiro 技术详解
java·apache
向前阿、3 小时前
数据结构从入门到实战————栈
c语言·开发语言·数据结构·程序人生
yuriy.wang3 小时前
Spring IOC源码篇六 核心方法obtainFreshBeanFactory.parseCustomElement
java·后端·spring
.鸣3 小时前
idea学习日记10: 字符串相关类的底层原理
java·学习
在未来等你3 小时前
Kafka面试精讲 Day 24:Spring Kafka开发实战
java·spring boot·面试·kafka·消息队列·spring kafka·@kafkalistener
龙茶清欢4 小时前
1、Lombok入门与环境配置:理解Lombok作用、配置IDE与构建工具
java·spring boot·spring cloud