標籤:鏈表 ring swa 可見 輸出 object nbsp 簡化 osi
棧是限制插入和刪除僅僅能在一個位置上進行的表。該位置是表的末端,叫做棧的頂top。對棧的基本操作有進棧push和出棧pop,前者相當於插入。後者這是刪除最後插入的元素。
棧有時又叫先進先出FIFO表。
因為棧操作是常數時間。因此除非在特殊情況下,棧不會產生明顯改進。
棧的第一種實現方法是使用單鏈表。通過在表的頂端插入來實現push,通過刪除表頂端元素實現pop。top操作僅僅是返回頂端元素的值。另外一種實現方法是使用數組,避免了鏈並且是更流行的解決方式。棧的棧頂用topOfStack來指向表示,對於空棧該值為-1。為將某個元素x推入棧中,我們使topOfStack加1然後置theItems[topOfStack]=x。
為了彈出棧頂元素,pop()返回theItems[topOfStack]然後topOfStack減1。
這些操作不僅以常數執行,並且是以非常快的常數時間執行。在某些機器上,若在帶有自增和自減定址功能的寄存器上操作,則整數的push和pop都能夠寫成一條機器指令。現代的電腦將棧操作作為指令系統的一部分,由此可見,棧非常可能是電腦在數組之後最主要的資料結構。
下面是一個用數組實現的棧,結構和數組非常像。但簡化了操作,當中的main函數用作測試:
import java.util.Iterator;import java.util.NoSuchElementException;public class MyStack<AnyType> implements Iterable<AnyType> {private static final int DEFAULT_CAPACITY = 10;private int theSize;private AnyType[] theItems;private int topOfStack;public MyStack() {clear();}public void clear() {theSize = 0;topOfStack = -1;ensureCapacity(DEFAULT_CAPACITY);}public int size() {return theSize;}public boolean isEmpty() {return size() == 0;}public void trumToSize() {ensureCapacity(size());}@SuppressWarnings("unchecked")public void ensureCapacity(int newCapacity) {if (newCapacity < size()) {return;}AnyType[] old = theItems;theItems = (AnyType[]) new Object[newCapacity];for (int i = 0; i <= topOfStack; i++) {theItems[i] = old[i];}theSize = newCapacity;}public AnyType top() {if (size() == 0) {throw new NullPointerException();}return theItems[topOfStack];}public AnyType pop() {if (size() == 0) {throw new NullPointerException();}return theItems[topOfStack--];}public void push(AnyType x) {if (topOfStack + 1 == size()) {ensureCapacity(size() * 2 + 1);}theItems[++topOfStack] = x;}@Overridepublic Iterator<AnyType> iterator() {return new StackIterator();}private class StackIterator implements Iterator<AnyType> {private int current = 0;public boolean hasNext() {return current <= topOfStack;}public AnyType next() {if (!hasNext()) {throw new NoSuchElementException();}return theItems[current++];}}public static void main(String[] args) {MyStack<Integer> stack = new MyStack<Integer>();stack.push(1);stack.push(2);stack.push(3);stack.pop();stack.push(4);stack.push(5);Iterator<Integer> iterator = stack.iterator();while (iterator.hasNext()) {System.out.print(iterator.next() + " ");}}}輸出結果:
1 2 4 5
資料結構(Java語言)——Stack簡單實現