[栈] 链表实现的栈

直接上代码

public class LinkedStack<E> {

    private Node<E> head = null;

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

    public E peek() {
        if(isEmpty()) {
            return null;
        }
        return head.data;
    }

    public E pop() {
        if(isEmpty()) {
            return null;
        }
        E out = head.data;
        head = head.next;
        return out;
    }

    public void push(E data) {
        Node<E> temp = head;
        head = new Node<>(data);
        head.next = temp;
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        for(int i = 1; i < 15; i++) {
            stack.push(i);
        }
        while (stack.peek() != null) {
            System.out.println(stack.pop());
        }
    }
}

控制面板打印如下

14
13
12
11
10
9
8
7
6
5
4
3
2
1

你可能感兴趣的:(数据结构)