java泛型实现链式栈

来源:互联网 发布:stm32单片机项目大全 编辑:程序博客网 时间:2024/06/06 03:24
public class LinkedStack<T> {private Node<T> top;public LinkedStack() {this.top = new Node<T>();}public void push(T element) {top = new Node<T>(element, top);}public T pop() {T result = top.val;if(!top.end()) {top = top.next;}return result;}class Node<U> {U val;Node<U> next;public Node() {this.val = null;this.next = null;}public Node(U val, Node<U> next) {this.val = val;this.next = next;}private boolean end() {return val == null && next == null;}}public static void main(String[] args) {LinkedStack<String> stack = new LinkedStack<String>();for(String str : "this is a test".split(" ")) {stack.push(str);}String tmp;while((tmp = stack.pop()) != null) {System.out.println(tmp);}}}

参考《Java 编程思想》

0 0
原创粉丝点击