栈的实现(一)——使用数组实现栈

栈是我们在学习中的一个重要的数据结构,栈具有后进先出(LIFO)的特征,在Java中已经定义好了一个栈,继承自Vector。实现栈的方式有很多种,可以使用数组,链表等等。以下的栈是我用数组实现的

package cn.jxustnc.stack;

import java.util.Arrays;

import cn.jxustnc.exception.StackOutOfIndexException;

public class Stack {
	/**
	 * 1.使用数组当作储存数据的底层结构 2.实现数组的LIFO(Last in First out)
	 * 3.用户可以知道stack的底层元素,可以压栈,出栈 4.知道栈的大小
	 */
	// 底层储存载体
	private Object[] theArray;
	// 栈顶
	private int topOfStack;

	/**
	 * 初始化栈,刚开始栈顶应该在0处
	 * 
	 */
	public Stack() {
		
		theArray = new Object[0];
		
		topOfStack = theArray.length;
	}

	/**
	 * 返回栈的大小,如果为空栈则返回-1
	 * 
	 * @return
	 */
	public int size() {
		if (theArray.length > 0) {
			return theArray.length;
		} else {
			return -1;
		}
	}

	/**
	 * 扩容,每次的扩容量为1
	 * 
	 */
	private void ensureCapacity(int lenth) {
		
		Object[] oldTheArray = theArray;
		
		if (lenth > 0) {
			Object[] newTheArray = new Object[theArray.length &

你可能感兴趣的:(数据结构)