package com.lgdx.yidianyi;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* 能自动调整空间大小的stack
* @author zsx
*
* @param <T>
*/
public class ResizingArrayStack<T> implements Iterable<T>{
private T[] arr;//存元素的数组
private int num;//数组中元素的个数
public ResizingArrayStack(){
arr = (T[])new Object[2];
num = 0;
}
/**
* stack里元素的个数
* @return
*/
public int elementsSize(){
return num;
}
/**
* 返回当前stack的大小
* @return
*/
public int stackSize(){
return arr.length;
}
/**
* 判断stack是否为空
* @return
*/
public boolean isEmpty(){
return num == 0;
}
/**
* 往stack里添加元素
* @param t
*/
public void push(T t){
if(num == arr.length){
resizeArray(2*arr.length);
}
arr[num++] = t;
}
/**
* 删除最后一个元素并返回
* @return
*/
public T pop(){
if(isEmpty()){
throw new NoSuchElementException("stack underflow");
}
T t = arr[--num];
arr[num] = null;
if(num > 0 && num == arr.length/4){
resizeArray(arr.length/2);
}
return t;
}
/**
* 返回stack元素
* @return
*/
public T peek(){
if(isEmpty()){
throw new NoSuchElementException("stack underflow");
}
return arr[num - 1];
}
/**
* 改变数组的大小
* @param i
*/
private void resizeArray(int i) {
T[] temp = (T[])new Object[i];
int arraySize = num;
for(int j = 0;j < arraySize;j++){
temp[j] = arr[j];
}
arr = temp;
}
@Override
public Iterator<T> iterator() {
return new ReverseArrayIterator();
}
public class ReverseArrayIterator implements Iterator<T>{
private int i;
public ReverseArrayIterator(){
i = num - 1;
}
@Override
public boolean hasNext() {
return i >= 0;
}
@Override
public T next() {
if(!hasNext()){
throw new NoSuchElementException();
}
return arr[i--];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public static void main(String[] args) {
ResizingArrayStack<String> resizingArrayStack = new ResizingArrayStack<String>();
resizingArrayStack.push("a");
resizingArrayStack.push("b");
resizingArrayStack.push("c");
resizingArrayStack.pop();
resizingArrayStack.pop();
System.out.println(resizingArrayStack.peek());
System.out.println(resizingArrayStack.elementsSize());
System.out.println(resizingArrayStack.stackSize());
Iterator<String> iterator = resizingArrayStack.iterator();
while(iterator.hasNext()){
String ele = iterator.next();
System.out.println(ele);
}
}
}
通过自适应调整数组大小实现Stack
最新推荐文章于 2024-08-29 09:59:54 发布