链栈实现算法 - Java 学习笔记(26)

    技术2022-05-11  37

     看了看以前的数据结构课本

    把C语言的算法改成Java的  写了个链栈的算法 (JRE中Stack类在java.util包里)

    // Coding by zhaohongliang public   class  LinkStackTest  {    public static void main(String[] args) {        LinkStack<Integer> ls =new LinkStack<Integer>();        Integer intgr = null;        for (int i=0;i<100;i++{            intgr = new Integer(i);            ls.push(intgr);        }        while(!ls.empty()) {            System.out.print(ls.pop()+"  ");        }    }} class  LinkStack < T >   {    private T data;    private LinkStack<T> next;    public LinkStack() {        data = null;        next = null;    }    public void push(T item) {        LinkStack<T> temp = next;        next = new LinkStack<T>();        next.next = temp;        next.data = item;    }    public boolean empty() {        return next==null ? true : false;    }    public T peek() {        if(empty()) throw new EmptyStackException();        return next.data;    }    public T pop() {        if(empty()) throw new EmptyStackException();        LinkStack<T> temp = next;        next = next.next;        return temp.data;    }} class  EmptyStackException  extends  RuntimeException  {} // 在java.util包里也有EmptyStackException

    最新回复(0)