标签:java 1.1 实现 public isEmpty 数组 ArrayStack Java stack
1.1. 栈的数据结构
栈是一种先进后出的数据结果,只能在一端(称为栈顶(top))对数据项进行插入和删除。
1.2. Java实现
StackTest |
package ch04;
public class StackTest {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(10);
System.out.println("isEmpty: "+stack.isEmpty());
for(int i = 0;i<10;i++){
stack.push(i);
}
System.out.println("isFull: "+stack.isFull());
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}
class ArrayStack{
private int[] arrInt;//内置数组
private int top;//栈顶指针
public ArrayStack(int size){
this.arrInt = new int[size];
top = -1;
}
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty(){
return -1 == top;
}
/**
* 判断栈是否已满
* @return
*/
public boolean isFull(){
return arrInt.length -1 == top;
}
/**
* 向栈顶插入一个元素
* @param item
*/
public void push(int item){
if(isFull()){
throw new RuntimeException("栈已满");
}
arrInt[++top] = item;
}
/**
* 从栈顶取出一个元素
* @return
*/
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈为空");
}
return arrInt[top--];
}
}
|
结果如下:
isEmpty: true
isFull: true
9
8
7
6
5
4
3
2
1
0
标签:java,
1.1,
实现,
public,
isEmpty,
数组,
ArrayStack,
Java,
stack
From: https://blog.51cto.com/u_6784072/6216846