美文网首页
Java 实现Stack

Java 实现Stack

作者: AlanFu | 来源:发表于2018-06-03 21:25 被阅读0次
Stack是一直先进后出的数据结构,先进后出在现实生活与计算机世界都很常见。作为开发者很有必要熟悉其实现。
/**
 * 内部链式存储机制
 * 2018/6/3
 * StoneFu
 */
public class LinkedStack<T> {
    //内部节点类
    private static class Node<U>{
        U item;
        Node<U> next;
        Node(){item=null;next=null;}
        Node(U item,Node<U> next){
            this.item=item;
            this.next=next;
        }
        boolean end(){return item==null&& next==null;}


    }
    //顶点哨兵
    private Node<T> top=new Node<T>();
    //入栈
    public void push(T item){
        top=new Node<>(item,top);
    }
  //出栈
    public T pop(){
        T result=top.item;
        if(!top.end()){
            top=top.next;
        }
        return result;
    }



}

测试代码

 @Test
    public void testLinkedStack(){
        LinkedStack<String> lss=new LinkedStack<>();
        for(String s:"i love you".split(" ")){
            lss.push(s);
        }
        String s;
        while ((s=lss.pop())!=null){
            System.out.println(""+s);
        }
    }

相关文章

网友评论

      本文标题:Java 实现Stack

      本文链接:https://www.haomeiwen.com/subject/wmdssftx.html