用接口实现堆栈

//define an integer stack interface.
interface IntStack
{
	void push(int item); //store an item
	int pop();
}

//An implementtation of IntStack that uses fixed storage.
class FixedStack implements IntStack
{
	private int stck();
	private int tos;
	//allocate and initialize stack
	FixedStack(int size)
	{
		stck = new int[size];
		tos = -1;
	}
	//push an item onto the stack
	public void push(int item)
	{
		if(tos == stck.length-1)  //use length member
			System.out.println("Stack is full.");
		else
			stck[++tos] = item;
	}
	//pop an item from the stack
	public int pop()
	{
		if(tos < 0)
		{
			System.out.println("Stack underflow.");
			return 0;
		}
		else
			return stck[tos--];
	}
}

class IFTest
{
	public static void main(String args[])
	{
		FixedStack mystack1 = new FixedStack(5);
		FixedStack mystack2 = new FixedStack(8);
		//push some numbers onto the stack
		for(int i=0; i<5; i++)  mystack1.push(i);
		for(int i=0; i<8; i++)  mystack2.push(i);
		//pop those numbers off the stack
		System.out.println("Stack in mystack1;");
		for(int i=0; i<5; i++)
			System.out.println("mystack1.pop()");
		System.out.println("Stack in mystak2:");
		for(int i=0; i<8; i++)
			System.out.println("mystack2.pop()");
	}
}


//IntStack另一个实现,使用相同的interface定义来创建一个动态堆栈
//Implement a "growable" stack
class DynStack implements IntStack
{
	private int stck[];
	private int tos;
	//allocate and initialize stack
	DynStack(int size)
	{
		stck = new int[size];
		tos = -1;
	}
	
	//push an item onto the stack
	public void push(int item)
	{
		//if stack is full, allocate a larger stack
		if(tos == stck.length-1)
		{
			int temp[] = new int[stck.length * 2];
			for(int i=0; i<stck.length; i++)  temp[i] = stck[i];
			stck = temp;
			stck[++tos] = item;
		}	
		else
			stck[++tos] = item;
	}

	//pop an item from the stack
	public int pop()
	{
		if(tos < 0)
		{
			System.out.println("Stack underflow.");
			return 0;
		}
		else
			return stck[tos--];
	}
}

class IFTest2
{
	public static void main(String args[])
	{
		DynStack mystack1 = new DynStack(5);
		DynStack mystack2 = new DynStack(8);
		//these loops cause each stack to grow
		for(int i=0; i<12; i++)  mystack1.push(i);
		for(int i=0; i<20; i++)  mystack2.push(i);
		System.out.println("Stack in mystack1:");
		for(int i=0; i<12; i++)
			System.out.println(mystack2.pop());
		System.out.println("Stack in mystack2:");
		for(int i=0; i<20; i++)
			System.out.println(mystack2.pop());
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值