Java用链表实现栈

上一篇实现了队列,这一篇我们实现栈。

栈是后入先出的数据结构。

链表中插入数据有头插法尾插法,本篇我们使用头插法。

不多说直接上代码

链表的节点定义和上一篇使用的是同一个,可以参考上一篇。

public class StackImpl<T> {
    private Element<T> top=null;

    public boolean push(T newElement){
        Element<T> element=new Element<T>();
        element.setValue(newElement);
        if(top==null)
            top=element;
        else
        {
            element.setNext(top);
            top=element;
        }
        return  true;
    }
    public  T pop(){
        T result=null;
        if(top==null)
            return  null;
        else {
           result=top.getValue();
            top=top.getNext();
        }
        return  result;
    }
    public T peek(){
        return top.getValue();
    }
}

猜你喜欢

转载自blog.csdn.net/zs742946530/article/details/83118818
今日推荐