package com.loong.datastructure;
/**
* 学习栈结构
*
* @author Loong
*
*/
public class Stack {
private Object[] stack = new Object[100];
private int top = -1;
/**
* 获取栈顶元素
*
* @return
*/
public Object getTop() {
if (stack == null) {
throw new RuntimeException("栈未初始化");
}
if (isStackEmpty()) {
throw new RuntimeException("栈已空");
}
return stack[top];
}
/**
* 压栈
*
* @param o
*/
public void push(Object o) {
if (stack == null) {
throw new RuntimeException("栈未初始化");
}
if (isStackFull()) {
throw new RuntimeException("栈向上溢出");
}
stack[++top] = o;
}
/**
* 退栈
*
* @return
*/
public Object pop() {
if (stack == null) {
throw new RuntimeException("栈未初始化");
}
if (isStackEmpty()) {
throw new RuntimeException("栈向下溢出");
}
return stack[top--];
}
/**
* 判断栈是否已满
*
* @return
*/
public boolean isStackFull() {
if (stack == null) {
throw new RuntimeException("栈未初始化");
}
return stack.length - 1 == top;
}
/**
* 判断栈是否为空
*
* @return
*/
public boolean isStackEmpty() {
if (stack == null) {
throw new RuntimeException("栈未初始化");
}
return top == -1;
}
/**
* 初始化栈
*
* @return
*/
public int initStack() {
return top = -1;
}
}
学习栈结构
最新推荐文章于 2024-07-10 21:37:49 发布