利用泛型模擬棧結構實現內部鏈式儲存結構

zk郭同學發表於2020-11-01

我們使用LinkedList可以很容易模擬出棧,現在我們使用泛型來實現棧,模擬內部鏈式儲存機制

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<>();
	//push方法就是模擬進棧操作,會建立一個新的物件,把它連結到前一個物件上。
	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) {
		String[] s = {"a","b","c","d"};
		LinkedStack<String> li = new LinkedStack<String>();
		for(String i : s) {
			li.push(i);
		}
		String s1;
		while((s1 = li.pop()) != null) {
			System.out.println(s1);
		}
	}
}

在這裡插入圖片描述

相關文章