class LinkedStack<T> {
    private Node top;
    private int size;

    /**
     * 初始化栈
     */
    public LinkedStack() {
        top = null;
        size = 0;
    }

    /**
     * 判断栈是否为空
     * 
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 清空栈元素
     */
    public void clear() {
        top = null;
        size = 0;
    }

    /**
     * 获取栈的大小
     * 
     * @return
     */
    public int length() {
        return size;
    }

    /**
     * 将一个数据入栈
     * 
     * @param data
     * @return
     */
    public boolean push(T data) {
        Node node = new Node(data);
        node.pre = top;
        top = node;
        size++;
        return true;
    }

    /**
     * 将数据出栈,并删除
     * 
     * @return
     */
    public T pop() {
        if (top != null) {
            Node node = top;
            top = top.pre;
            size--;
            return node.data;
        }
        return null;
    }

    /**
     * 获取栈顶元素,但不删除该栈元素数据
     * 
     * @return
     */
    public T peek() {
        if (top != null) {
            return top.data;
        }
        return null;
    }

    /**
     * 节点类
     * 
     * @author John
     *
     */
    private class Node {
        Node pre;
        T data;

        public Node(T data) {
            this.data = data;
        }
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-02-22
  • 2021-07-27
  • 2021-11-09
  • 2022-02-28
  • 2021-07-09
  • 2022-03-03
猜你喜欢
  • 2022-02-08
  • 2021-12-11
  • 2022-12-23
  • 2021-10-14
  • 2021-12-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案