【數據結構】棧的數組實現

import java.util.EmptyStackException;

public class ArrayStack<T> implements Cloneable
{
	private T[] data;
	private int manyItems;
	
	// 默認構造函數
	public ArrayStack()
	{
		final int INITIAL_CAPACITY = 10;
		manyItems = 0;
		data = (T[]) new Object[INITIAL_CAPACITY];
	}
	
	public ArrayStack(int initialCapacity)
	{
		manyItems = 0;
		data = (T[]) new Object[initialCapacity];
		
	}
	
	// 生成棧的一個副本
	public ArrayStack<T> clone()
	{
		ArrayStack<T> answer;
		try
		{
			answer = (ArrayStack<T>)super.clone();
		} catch (CloneNotSupportedException	e)
		{
			throw new RuntimeException("this class does not implement Cloneable.");
		}
		
		answer.data = data.clone();
		return answer;
	}
	
	// 改變棧當前的容量
	public void ensureCapacity(int minimumCapacity)
	{
		T[] newArr;
		if (data.length < minimumCapacity)
		{
			newArr = (T[])new Object[minimumCapacity];
			System.arraycopy(data, 0, newArr, 0, manyItems);
			data = newArr;
		}
	}
	
	// 存取方法,用於確定棧的當前容量。
	public int getCapacity()
	{
		return data.length;
	}
	
	// 判斷是否爲空
	public boolean isEmpty()
	{
		return (manyItems == 0);
	}
	
	// 在不移除棧頂元素的情況下,獲得棧頂數據項的值
	public T peek()
	{
		if (manyItems == 0)
		{
			throw new EmptyStackException();
		}
		return data[manyItems -1];
	}
	
	// 獲得棧頂數據項,並將其從棧中移出
	public T pop()
	{
		if (manyItems == 0)
		{
			throw new EmptyStackException();
		}
		// 獲得棧頂項
		T answer = data[manyItems - 1];
		manyItems = manyItems - 1;
		data[manyItems] = null;
		
		return answer;		
	}
	
	// 將一個數據項壓入棧中,新的數據項可以是空引用
	public void push(T item)
	{
		if (data.length == manyItems)
		{
			ensureCapacity(manyItems*2 + 1);
		}
		data[manyItems] = item;
		manyItems++;
	}
	
	// 用於確定棧中數據項個數的存取方法
	public int size()
	{
		return manyItems;
	}
	
	public void trimToSize()
	{
		T trimmedArray[];
		if (data.length == manyItems)
		{
			trimmedArray = (T[]) new Object[manyItems];
			System.arraycopy(data, 0, trimmedArray, 0, manyItems);
			data = trimmedArray;
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章