首页 > 编程 > Java > 正文

使用java实现栈

2019-11-10 20:33:21
字体:
来源:转载
供稿:网友
public class StackTest<T> {    public static class Node<U>{        public U item;        public Node next;        public Node() {            this.item = null;            this.next = null;        }        public Node(U item, Node<U> next) {            this.item = item;            this.next = next;        }        public boolean end() {            return item == null && next == null;        }    }    PRivate Node<T> top = new Node<T>();    public void push(T item) {        top = new Node<T>(item, top);    }    public T pop() {        T result = top.item;        if (!top.end()) {            top = top.next;        }        return result;    }    public static void main(String[] args) {        StackTest<String> st = new StackTest<>();        for (String str : "I love java".split(" ")) {            st.push(str);        }        while (!st.top.end()) {            System.out.println(st.pop());        }    }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表