数组实现栈
栈是一种后进先出的数据结构LIFO(Last In First Out )
package com.yang.review;
/**
* -----------栈-------------
* * 下面的是使用数组实现栈 *
* * @author 阳
* * *栈是一种后进先出的数据结构 *
* *----------LIFO------------
*/
public class Stack {
//定义数组
Object[] data;
//堆栈长度
int maxSize;
//栈顶位置
int top;
//构造函数对于数组大小进行初始化
public Stack(int maxSize) {
this.maxSize = maxSize;
data = new Object[maxSize];
top = -1;
}
/**
* 获取堆栈长度 * @return 堆栈长度
*/
public int getSize() {
return maxSize;
}
/**
* 返回栈中元素的个数 * @return 元素个数
*/
public int getElementCount() {
return top;
}
/**
* 判断是否为空 * @return
*/
public boolean isEmpty() {
return top == -1;
}
/**
* 判断栈是否已经满栈 * @return
*/
public boolean isFull() {
return top + 1 == maxSize;
}
/**
* 向栈中添加数据 * @param data * @return
*/
public boolean push(Object data) {
if (isFull()) {
System.out.println("该栈已经满了!");
return false;
}
this.data[++top] = data;
return true;
}
/**
* 出栈操作 * @return * @throws Exception
*/
public Object pop() throws Exception {
if (isEmpty()) {
System.out.println("该栈已经是空栈了!");
throw new Exception("栈已空!");
}
return this.data[top--];
}
/**
* 返回栈顶元素 * @return
*/
public Object peek() {
return data[getElementCount()];
}
public static void main(String[] args) throws Exception {
//初始化栈大小
Stack stack = new Stack(20);
//测试入栈操作
stack.push(new String("1"));
stack.push(new String("2"));
stack.push(new String("3"));
stack.push(new String("4"));
stack.push(new String("5"));
//测试栈顶元素方法
System.out.println("栈顶元素:" + stack.peek());
//测试出栈操作
while (stack.top >= 0) {
System.out.println("当前出栈元素:" + stack.pop());
}
}
}
测试结果如下: