栈的图示

23-咸鱼学Java-Java中的栈_Stack


代码

/**
* 栈
* @author 焦焱
*
*/
public class Stack {
/**
* 栈顶标记
*/
int top;
/**
* 栈内元素
*/
int[] elem;
/**
* 无参构造
*/
public Stack()
{
this(10);
}
/**
* 有参构造
* @param size
*/
public Stack(int size) {
this.top = 0;
this.elem = new int[size];
}

/**
* 入栈
* @param val
* @return
*/
public boolean push(int val)
{ //先判断是否满
if(isFull()){
return false;
}
//如果不为空,赋值,并且栈顶往上走一位
this.elem[this.top++] = val;
return true;
}
/**
* 出栈
* @return
*/
public int pop() {
//先判断是否为空
if(isEmpty()){
System.out.println("当前栈为空");
return -1;
}
//返回当前栈顶减一位置的的元素,并且栈顶往下减一。
return elem[--top];
}
/**
* 获得栈顶元素
* @return
*/
public int getTop()
{ //如果为空返回-1,如果
return isEmpty()?-1:elem[this.top-1];
}
/**
* 判断是否满
* @return
*/
public boolean isFull()
{
return top==this.elem.length;
}
/**
* 判断是否空
* @return
*/
public boolean isEmpty()
{
return top==0;
}
/**
* 显示当前栈内所有元素
*/
public void show()
{
System.out.println("\t栈顶------->栈底");
System.out.print("当前栈数据为:");
for (int i = top-1; i >=0; i--) {
System.out.print(elem[i]+" ");
}
System.out.println();
}
}

测试

public static void main(String[] args) {
Stack t = new Stack();
int stackLength = 5;
for (int i = 0; i < stackLength; i++) {
t.push(i);
}
t.show();
for (int i = 0; i < stackLength; i++) {
System.out.println(t.pop()+" ");
}
}

结果
​​​栈顶------->栈底
当前栈数据为:4 3 2 1 0
4
3
2
1
0