数组栈

数组栈

栈类

class ArrayStack {
	private int[] stack;	//数组栈
	private int MaxSize;	//栈的容量
	private int top;		//栈的指针
	public ArrayStack(int MaxSize){	
		this.MaxSize = MaxSize;		
		stack = new int[this.MaxSize];
		top = -1;				//栈为空时,指针指向-1
	}

判断栈满或栈空

public boolean isFull(){		//判断栈满
		return top == MaxSize-1;
	}
	public boolean isEmpty(){		//判断栈空
		return top == -1;
	}

入栈

public void push(int value){	//入栈
		if(isFull()){				
			System.out.println("栈满");
			return;
		}
		top++;						//指针移动
		stack[top] = value;			//将数据入栈
	}

出栈

public void pop(){				//出栈
		if(isEmpty()){
			System.out.println("栈空");
			return;
		}
		int value = stack[top];		//将数据取出
		top--;						//指针移动
		System.out.println(value);	//打印
	}

打印栈中元素

public void show(){				//显示栈的元素
		if(isEmpty()){
			System.out.println("栈空");
			return;
		}
		for(int i= top;i<=0;i--){
			System.out.println(stack[i]);
		}

代码

package stack;

public class ArrayStackDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayStack stack = new ArrayStack(3);
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		System.out.println("--------");
		stack.show();
		System.out.println("-------");
		stack.pop();
		stack.pop();
		stack.pop();
		stack.pop();
		
	}

}
class ArrayStack {
	private int[] stack;	//数组栈
	private int MaxSize;	//栈的容量
	private int top;		//栈的指针
	public ArrayStack(int MaxSize){	
		this.MaxSize = MaxSize;		
		stack = new int[this.MaxSize];
		top = -1;				//栈为空时,指针指向-1
	}
	public boolean isFull(){		//判断栈满
		return top == MaxSize-1;
	}
	public boolean isEmpty(){		//判断栈空
		return top == -1;
	}
	public void push(int value){	//入栈
		if(isFull()){				
			System.out.println("栈满");
			return;
		}
		top++;						//指针移动
		stack[top] = value;			//将数据入栈
	}
	public void pop(){				//出栈
		if(isEmpty()){
			System.out.println("栈空");
			return;
		}
		int value = stack[top];		//将数据取出
		top--;						//指针移动
		System.out.println(value);	//打印
	}
	public void show(){				//显示栈的元素
		if(isEmpty()){
			System.out.println("栈空");
			return;
		}
		for(int i= top;i<=0;i--){
			System.out.println(stack[i]);
		}
	}
	
	
	
	
	
	
	
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值