Java数据结构之——栈:用链表实现

class Node{
    E data;
    Node next = null;
    public Node(E data){
        this.data = data;
    }
}

public class ListStack{
    Node top = null;
    public boolean empty(){
        return top == null;
    }
    
    //头插法插入新节点,实现入栈
    public void push(E data){
        Node newNode = new Node(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;
    }
}

 

你可能感兴趣的:(Java基础学习)