1. 程式人生 > >java泛型實現鏈式棧

java泛型實現鏈式棧

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 程式設計思想》