package Stack;
import org.junit.Test;
import java.util.Stack;
//数组实现一个栈:此时栈中数据元素类型为整形
public class MyStack_Array<T> {
//存数据的数组
T[] data;
//栈的最大长度
private int size;
//栈顶的位置
private int top;
//初始化栈,并指定栈的初始高度
public MyStack_Array(int size) {
this.size = size;
data = (T[])new Object[size];
top = -1;
}
//获得栈的长度(高度)
public int getSize() {
return size;
}
//返回一个代表栈顶的位置的整数 基准为-1
public int getTop() {
return top;
}
/**
* 判断是否为空栈
* @return
*/
public boolean isEmpty() {
return top == -1;
}
/**
* 判断是否为满栈
* @return
*/
public boolean isFull() {
return (top+1) == size;
}
/**
* 压栈操作
* @param data
* @return
*/
public boolean push(T data) {
if(isFull()) {
System.out.println("the stack is full!");
return false;
} else {
top++; //栈顶指针上升一
this.data[top] = data; //将新数据压入
return true;
}
}
/**
* 弹栈操作
* @return
* @throws Exception
*/
public T pop() throws Exception {
if(isEmpty()) {
throw new Exception("the stack is empty!");
} else {
return this.data[top--];
}
}
/**
* 获取栈顶的元素,但不弹栈
* @return
*/
public T peek() {
return this.data[getTop()];
}
public static void main(String[] args) {
MyStack_Array stack = new MyStack_Array(20);
stack.push(0);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Now the top_num is:" + stack.peek());
while(! stack.isEmpty()) {
try {
System.out.println(stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
java数据结构——数组实现栈结构
猜你喜欢
转载自blog.csdn.net/qq_40692753/article/details/82984962
今日推荐
周排行