Java實現棧Stack_棧內部使用數組存儲結構java
抽象數據類型棧的定義:數組
棧(stack),是限定在表尾進行插入或刪除操做的線性表,所以對棧來講表尾有其特殊的含義,稱爲棧頂,相應的,表頭端稱爲棧底。不含元素的空表稱爲空棧。數據結構
棧-後進先出(last in first out)this
棧-順序棧-棧的順序存儲結構是利用一組地址連續的存儲單元依次存放自棧底到棧頂的數據元素線程
具體可參考java.util.Stack;內部已實現的數據結構棧,這裏只是爲了體會Java中高級數據結構的實現過程。code
貼代碼對象
package hash; /** * Created with IntelliJ IDEA. * User: ASUS * Date: 14-9-14 * Time: 下午7:14 * To change this template use File | Settings | File Templates. */ public class CustomStack<E> { protected E[] elementData; //棧內部使用數組來存儲 protected int elementCount; // 棧當前的元素數量 protected int capacityIncrement; //容量增加 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; public CustomStack(int initialCapacity, int capacityIncrement) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); this.elementData = (E[]) new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } /** * 元素入棧 * 同步方法 * 這也就是同步方法,他鎖定的是調用這個同步方法對象。 * 也就是說,當一個對象P在不一樣的線程中執行這個同步方法時,他們之間會造成互斥,達到同步的效果。 */ public synchronized E push(E item) { //當棧容量已滿時,擴大棧容量 int minCapacity = elementCount + 1; if (minCapacity - elementData.length > 0) { //說明當前棧已滿 int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } if (newCapacity - MAX_ARRAY_SIZE > 0) { newCapacity = (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } E[] copy = (E[]) new Object[newCapacity]; //新的數組 System.arraycopy(elementData, 0, copy, 0, elementData.length); //數組的拷貝 elementData = copy; } elementData[elementCount++] = item; return item; } /** * 棧頂元素出棧,同時移除該元素 */ public synchronized E pop() throws Exception { E obj; int index = elementCount - 1; //最後一個元素的索引 if (index < 0) { throw new Exception("數組越界"); } obj = elementData[index]; elementData[index] = null; //同時移除元素gc自動清除內存垃圾 elementCount--; return obj; } /** * 棧頂元素出棧,而不從棧中移除改元素 */ public synchronized E peek() throws Exception { E obj; int index = elementCount - 1; //最後一個元素的索引 if (index < 0) { throw new Exception("數組越界"); } obj = elementData[index]; return obj; } /** * 棧是否爲空 */ public synchronized boolean empty() { return elementCount == 0; } /** * 返回的是棧這種數據結構中的索引 * 不是數組的索引 * 直接遍歷棧內部存儲結構數組,定位元素 * * @param o * @return */ public synchronized int search(Object o) { int index = elementCount - 1; if (o == null) { for (int i = index; i >= 0; i--) { if (elementData[index] == null) { return elementCount - i; } } } else { for (int i = index; i >= 0; i--) { if (elementData[index].equals(o)) { return elementCount - i; } } } return -1; } public static void main(String args[]) throws Exception { CustomStack<String> stringCustomStack = new CustomStack<String>(12, 10); for (int i = 0; i < 200; i++) { stringCustomStack.push("lyx" + i); } System.out.println(stringCustomStack.peek()); System.out.println(stringCustomStack.pop()); System.out.println(stringCustomStack.elementCount); } }
========END========索引