使用数组实现固定大小的栈结构

使用数组实现固定大小的栈,很简单,水一水。

入栈规则:使用一个指针指向栈内元素的上一个位置,如果入栈,只需要在指针位置放入元素即可,然后指针再指向上一个位置,如果超出数组长度,则报错

出栈规则:返回指针指向位置的下一个元素,如果小于0,则报错


代码:

/*
 * 使用数组实现一个栈
 */
public class UsingArrayRealizeStack {
	
	public static int[] stack = new int[5];
	public static int size = 0; // 栈中已放入元素的个数
	public static int index = 0;// 栈的指针
	// 入栈
	public  void put(int value){
		if(index >= stack.length){
			throw new ArrayIndexOutOfBoundsException("the size more than bounds");
		}
		stack[index++] = value;
		size++;
	}
	// 出栈
	public  int poll(){
		if(index <= 0){
			throw new IllegalArgumentException("the size less than 0");
		}
		size--;
		return stack[--index];
	}
	// 栈顶元素
	public  Integer peek(){
		if(size == 0){
			return null;
		}
		return stack[size];
	}
	public static void main(String[] args) {
		UsingArrayRealizeStack stack = new UsingArrayRealizeStack();
		stack.put(1);
		System.out.println(stack.poll());// 1
		stack.put(1);
		stack.put(2);
		stack.put(3);
		stack.put(4);
		stack.put(5);
	//	stack.put(6);
		System.out.println(stack.poll());// 5
		System.out.println(stack.poll());// 4
		System.out.println(stack.poll());// 3
		System.out.println(stack.poll());// 2
		System.out.println(stack.poll());// 1
	}
}

测试结果:



猜你喜欢

转载自blog.csdn.net/smile_yangyue/article/details/79797989
今日推荐