栈
先进后出。push入栈,pop出栈,peek查看栈顶元素。数组实现栈有栈空,栈满。
数组实现栈
package com.simple.st;
/**
* @ClassName Stack
* @Author gg_girl
* @Date 2020/9/4
* @Description 栈类。有栈空,栈满。
* 操作:入栈push,出栈pop,peek查看栈顶元素,栈空,栈满判断,元素展示
* @Version 1.0
*/
public class Stack {
public int size;
public int top;
public int[] array;
public Stack(int size){
this.size = size;
this.top = -1; // -1栈空
this.array = new int[this.size];
}
public void push(int ele){
// push前判断栈是否满
this.array[++top] = ele;
}
public int pop(){
return this.array[top--];
}
public int peek(){
return this.array[top];
}
public boolean isEmpty(){
return this.top == -1;
}
public boolean isFull(){
return this.top == this.size - 1;
}
public void display() {
for(int i = 0; i <= this.top; i++){
System.out.print(this.array[i] + " ");
}
System.out.println();
}
}
package com.simple.st;
/**
* @ClassName StackApp
* @Author gg_girl
* @Date 2020/9/4
* @Description Stack类应用及测试
* @Version 1.0
*/
public class StackApp {
public static void main(String[] args) {
Stack stack = new Stack(4);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);// 1 2 3 4
System.out.println(stack.isFull());//true
stack.display();// 1 2 3 4
int ele = stack.pop(); // 4
System.out.println(ele);
stack.pop();//3
stack.pop(); // 2
stack.pop(); // 1
System.out.println(stack.isEmpty()); // true
}
}