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========索引