跳到主要内容

编写Java代码实现链栈 ?

参考答案:

以下是一个简单的链栈(链式栈)的Java实现。这个实现定义了一个Node类,用于存储栈的元素,以及一个LinkedStack类,它包含pushpoppeekisEmptysize等方法。

public class LinkedStack<T> {

    private Node<T> top;
    private int size;

    private static class Node<T> {
        T item;
        Node<T> next;

        Node(T item) {
            this.item = item;
        }
    }

    public LinkedStack() {
        top = null;
        size = 0;
    }

    public void push(T item) {
        Node<T> oldTop = top;
        top = new Node<>(item);
        top.next = oldTop;
        size++;
    }

    public T pop() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty");
        }
        T item = top.item;
        top = top.next;
        size--;
        return item;
    }

    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty");
        }
        return top.item;
    }

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

    public int size() {
        return size;
    }
}

在这个实现中,push方法将一个新的元素添加到栈顶,pop方法从栈顶移除一个元素并返回它,peek方法返回栈顶元素但不移除它,isEmpty方法检查栈是否为空,size方法返回栈中元素的数量。

请注意,这个实现没有包括任何线程安全的措施。如果你打算在多线程环境中使用这个栈,你可能需要添加一些同步机制以防止并发问题。