通过自适应调整数组大小实现Stack

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);
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值