標籤:java 鏈表 單鏈表 棧 資料結構
接下來讓我們看看,如何利用單鏈表結構來實現棧與隊列。由於棧的操作只限於棧頂元素,而單鏈表只有對首元素才能在O(1)時間內完成插入和刪除,故這裡把單鏈表的首節點作為棧頂,其餘元素依次排列。此外,為了保證getSize()方法也能夠在O(1)時間內完成,還需藉助一個執行個體變數來動態記錄棧中元素的數目。具體的實現如 代碼二.12 所示。
Node類 Java代碼見( Java 實現鏈表)
StackLink 類:
package com.list.stack;import java.util.Arrays;import com.stack.ExceptionStackEmpty;import com.list.stack.Node;public class StackList { //Declared size of stack list private static int size; //Declared element private static Node top; public StackList() { this.size = 0; this.top = null; } // Get the size of stack public int getSize() { if(isEmpty()) return 0; else return size; } // Get whether stack is empty public boolean isEmpty() { return size == 0; } // Get the top element of stack public Object top() throws ExceptionStackEmpty { if(isEmpty()) throw new ExceptionStackEmpty("Stack is empty!"); return top.getElement(); } // Push element to stack public void push(Object element){ Node newNode = new Node(element,top); top = newNode; size ++; } // Pop element from stack public Object pop() throws ExceptionStackEmpty { if(isEmpty()) throw new ExceptionStackEmpty("Stack is empty!"); Object container = top.getElement(); top = top.getNext(); size --; return container; } // Get the all elements of stack public void getAllElements() throws ExceptionStackEmpty { Node travelTop; travelTop = top; Object[] array = new Object[getSize()]; for(int i = 0;i < array.length;i ++ ){ array[i] = travelTop.getElement(); travelTop = travelTop.getNext(); } System.out.println("Get all elemnt: " + Arrays.toString(array)); }}
StackLinkTest 類:
package com.list.stack;import com.stack.ExceptionStackEmpty;public class StackListTest { public static void main(String[] args) throws ExceptionStackEmpty { //Test Class StackList StackList sl = new StackList(); System.out.println("Size of stack list: " + sl.getSize()); System.out.println("Is emplty? : " + sl.isEmpty()); sl.push(12); sl.push(13); sl.push(15); sl.push(17); sl.push(2); sl.push(6); sl.getAllElements(); System.out.println("Size of stack list: " + sl.getSize()); System.out.println("Is emplty? : " + sl.isEmpty()); //sl.getAllElements(); System.out.println(sl.pop()); System.out.println(sl.pop()); System.out.println(sl.pop()); System.out.println(sl.pop()); System.out.println(sl.pop()); System.out.println(sl.pop()); System.out.println("Size of stack list: " + sl.getSize()); System.out.println("Is emplty? : " + sl.isEmpty()); }}
測試結果:
Size of stack list: 0Is emplty? : trueGet all elemnt: [6, 2, 17, 15, 13, 12]Size of stack list: 6Is emplty? : false6217151312Size of stack list: 0Is emplty? : true
轉載請註明出處,謝謝!
http://blog.csdn.net/github_27609763/article/details/46476917
基於鏈表實現Java 自訂Stack隊列