java数据结构中栈的基本操作方法

基于链表实现的栈数据结构,支持泛型(FILO)


public class LinkedStack <E>{
    // 虚拟头节点,不存储实际元素,用于简化操作
    private final Node<E> head = new Node(null);

    //入栈操作:将元素压入栈顶
    public void push(E element) {
        // 创建新节点存储元素
        Node<E> node = new Node<>(element);
        // 新节点的next指向原栈顶节点
        node.next = head.next;
        // 头节点的next指向新节点,使新节点成为栈顶
        head.next = node;
    }

    //出栈操作:移除并返回栈顶元素
    public E pop() {
        // 检查栈是否为空
        if (isEmpty())
            throw new NoSuchElementException("栈为空");
        // 保存栈顶元素
        E e = head.next.element;
        // 头节点的next指向原栈顶的下一个节点,完成出栈
        head.next = head.next.next;
        return e;
    }

    //判断栈是否为空 
    public boolean isEmpty() {
        return head.next == null;
    }

    // 链表节点类,用于存储元素和指向下一个节点的引用
    private static class Node<E> {
        // 节点存储的元素
        private E element;
        // 指向下一个节点的引用
        private LinkedStack.Node<E> next;

        // 节点构造函数
        public Node(E e) {
            this.element = e;
        }
    }
}

基于链表实现的队列数据结构(FIFO),支持泛型

public class LinkedQueue<E> {
    // 虚拟头节点,指向队列第一个元素(若存在)
    private final Node<E> head = new Node<>(null);


    //入队操作:将元素添加到队列尾部
    public void offer(E element) {
        // 从头节点开始遍历寻找尾节点
        Node<E> tail = head;
        while (tail.next != null) {
            tail = tail.next;
        }
        // 在尾部添加新节点
        tail.next = new Node<>(element);
    }

    //操作:移除并返回队列头部元素
    public E poll() {
        if (isEmpty()) {
            throw new NoSuchElementException("队列为空");
        }
        // 获取头节点的下一个节点(即队列第一个元素)
        E e = head.next.element;
        // 跳过原头节点的下一个节点,实现删除
        head.next = head.next.next;
        return e;
    }
    
    //队列是否为空
    public boolean isEmpty() {
        return head.next == null;
    }


    //节点类(静态内部类)
    private static class Node<E> {
        private E element;        // 节点存储的元素
        private Node<E> next;     // 指向下一个节点的引用

        public Node(E e) {
            this.element = e;
        }
    }
}
分类: 数据结构 标签: 暂无标签

评论

暂无评论数据

暂无评论数据

目录