下压(LIFO)栈

//在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。
package example;
import java.util.*;

public class test {
	public static class ResizingArrayStack<Item> implements Iterable<Item> {

		private Item[] a = (Item[]) new Object[1];//栈元素
		private int N = 0;//元素数量
		public boolean isEmpty(){
			return N==0;
		}
		public int size(){
			return N;
		}
		private void resize(int max){//将栈移动到一个大小为max的新数组
			Item[] temp = (Item[]) new Object[max];
			for(int i = 0;i < N;i++){
				temp[i] = a[i];
			}
			a = temp;
		}
		public void push(Item item){//将元素添加到栈顶
			if(N == a.length)
				resize(2 * a.length);
			a[N++] = item;
		}
		public Item pop(){//从栈顶删除元素
			Item item = a[--N];
			a[N] = null;//避免对象游离
			if (N > 0 && N == a.length/4)
				resize(a.length/2);
			return item;
		}
		@Override
		public Iterator<Item> iterator() {
			// TODO Auto-generated method stub
			return new ReverseArrayIterator();
		}
		private class ReverseArrayIterator implements Iterator<Item>{//支持后进先出的迭代
			private int i = N;
			public boolean hasNext(){
				return i > 0;
			}
			public Item next(){
				return a[--i];
			}
			public void remove(){}
		}
	}
		
	public static void main(String args[]){
		ResizingArrayStack<String> a;
		a = new ResizingArrayStack<String>();
		a.push("asd");
		a.push("sdfd");
		for(String s : a){
			System.out.print(s + "\n");
		}
		
			
	}

	


}


转载于:https://my.oschina.net/stevenKelly/blog/389491

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值