数组实现堆栈——Java实现

package struct;


//接口
interface IArrayStack{
	//栈的容量
	int length();
	//栈中元素个数(栈大小)
	int size();
	//取栈顶元素
	Object top();
	//判断栈是否为空
	boolean isEmpty();
	//入栈
	Object pop();
	//出栈
	Object push(Object value);
	//清空栈
	void clear();
}


//实现接口的StackImpl类
class StackImpl implements IArrayStack{
	static Object[] arr;//数组
	private int top;//标记栈顶位置,并且表示栈的容量大小
	private static int MAXSIZE = 10;//数组的最大长度(常量)
	//构造方法 
	public StackImpl(){
		arr = new Object[MAXSIZE];
		top = 0;
	}
	//求堆栈容量
	public int length() {
		return MAXSIZE;
	}
	//求堆栈中元素的个数,即堆栈大小
	public int size(){
		return top;
	}
	//取栈顶元素
	public Object top() {
		return arr[top];
	}
	//判断堆栈是否为空
	public boolean isEmpty() {
		return (size() == 0);
	}
	//出栈
	public Object pop() {
		if(isEmpty()){
			System.out.println("The Stack is empty");
			return -1;
		}
		Object value = arr[top - 1];
		top--;
		arr[top -1] = null;
		return value;
	}
	//对栈进行扩容(每次扩容一倍)
		public void expand(){
			Object[] largerArr = new Object[size()*2];
			for(int index = 0;index < top;index++){
				largerArr[index] = arr[index];
			}
			arr = largerArr;
			MAXSIZE = arr.length;
		}
	//入栈
	public Object push(Object value) {
		//如果超过入栈元素数组长度
		if(top == arr.length){
			expand();
		}else{
			arr[top] = value;
			top++;	
		}
		return arr;
	}
	//打印堆栈中元素
	public static void print(){
		myPrint1(arr);
	}
	private static void myPrint1(Object[] obj){
		for(int i = 0;i < obj.length;i++){
			System.out.println(obj[i] + " ");
		}
	}
	//清空堆栈
	public void clear() {
		for(int i = top;i > 0;i--){
			arr[i] = null;
			top--;
		}
	}
}


//测试函数
public class ArrayStack {
	public static void main(String[] args) {
		IArrayStack stack = new StackImpl();
		System.out.println("==================栈中不存在元素测isEmpty函数================");
		System.out.println(stack.isEmpty());
		System.out.println("==================测length函数================");
		System.out.println( stack.length());
		System.out.println("==================测push及print函数================");
		stack.push("lemon");
		stack.push("hah");
		stack.push(1);
		stack.push(9);
		stack.push("lemon");
		stack.push("hah");
		stack.push(1);
		stack.push(9);
		stack.push("lemon");
		stack.push("hah");
		stack.push(1);
		stack.push(9);
		StackImpl.print();
		System.out.println("==================扩容后测length函数================");
		System.out.println(stack.length());
		System.out.println("==================测top函数================");
		System.out.println(stack.top());
		System.out.println("==================测size函数================");
		System.out.println( stack.size());
		System.out.println("==================测pop函数================");
		stack.pop();
		stack.pop();
		System.out.println( stack.size());
		System.out.println("==================栈中存在元素测isEmpty函数================");
		System.out.println(stack.isEmpty());
		System.out.println("==================clear后侧size函数================");
		stack.clear();
		System.out.println( stack.size());
	}
}


猜你喜欢

转载自blog.csdn.net/qq_40409115/article/details/79979931