Stack.java

package cn.meowrain.Datastructure.collection;

import java.util.NoSuchElementException;

public class Stack<E> {
    private final Node<E> head = new Node<>(null);

    public void push(E element){
        Node<E> node = new Node<>(element);
        node.next = head.next;
        head.next = node;
    }
    public E pop(){
        if(head.next == null){
            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 final E element;
        private Node<E> next;

        public Node(E e) {
            this.element = e;
        }

    }
}

StackRunner.java

package cn.meowrain.Datastructure;

import cn.meowrain.Datastructure.collection.Stack;

public class StackRunner {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("meowrain");
        stack.push("meow");
        stack.push("nice");
        String n = stack.pop();
        System.out.println(n);
    }
}