编程题:利用链表实现栈

孤街醉人 提交于 2019-12-01 07:23:27
class Node<E>{
    E data;
    Node<E> next = null;
    public Node(E data){
        this.data = data;
    }
}

class ListStack<E>{
    Node<E> top = null;
    public boolean empty(){
        return top == null;
    }

    //头插法插入新节点,实现入栈
    public void push(E data){
        Node<E> newNode = new Node<E>(data);
        newNode.next = top;
        top = newNode;
    }

    public E pop(){
        if(this.empty()){
            return null;
        }
        E data = top.data;
        top = top.next;
        return data;
    }

    public E peek(){
        if(empty())
            return null;
        return top.data;
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!