堆栈
认识堆栈
谈到所谓后进先出(Last in, First out)的概念,其实就如同自助餐中餐盘由桌面向上一个一个叠放,且去勇士由最上面先拿,这就是典型堆栈概念的应用
堆栈的运算
-
只能从堆栈的顶端访问数据
-
数据的访问符合"后劲先出"(Last in First out)
堆栈的数组实现
Stack类
package 堆栈的数组实现;
/**
* @author YanAemons
* @date 2021/10/6 16:02
*/
public class StackByArray {
private int[] stack;
private int top;
public StackByArray(int stack_size)
{
stack = new int[stack_size];
top = -1;
}
public boolean push(int data)
{
if (top >= stack.length)
{
System.out.println("堆栈已满");
return false;
}
else
{
stack[++top] = data;
return true;
}
}
public boolean isEmpty()
{
if (top == -1) return true;
else return false;
}
public int pop()
{
if (isEmpty()) return -1;
else return stack[top--];
}
}
其中top作为指向堆栈顶部的指针
Main类
package 堆栈的数组实现;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author YanAemons
* @date 2021/10/6 16:10
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader buf;
int value;
StackByArray stack = new StackByArray(10);
buf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入10个数据");
for (int i = 0; i < 10; i++)
{
value = Integer.parseInt(buf.readLine());
stack.push(value);
}
System.out.println("====================");;
while(!stack.isEmpty()) System.out.println("堆栈弹出顺序为:"+stack.pop());
}
}