栈的数据结构就是先进后出,先了解一下他的数据结构。
import java.util.Scanner;
/**
* @author xienl
* @description 栈
* @date 2022/5/16
*/
public class Main {
public static void main(String[] args) {
final String push = "push", pop = "pop", top = "top";
Scanner scanner = new Scanner(System.in);
// 输入次数
int num = scanner.nextInt();
MyStack myStack = new MyStack(num);
scanner.nextLine(); // 这个是个scanner的大坑,如果按了会车一定要加
for (int i = 0; i < num; i++){
String next = scanner.nextLine();
String[] split = next.split("\\s+");
if (split == null || split[0].isEmpty()){
return;
}
String str = split[0];
if (push.equals(str)){
if (split[1] == null || strTransForInt(split[1]) == -1){
return;
}
myStack.push(strTransForInt(split[1]));
} else if (pop.equals(str)){
myStack.pop();
} else if (top.equals(str)){
myStack.top();
} else {
return;
}
}
}
/**
* 字符串转整数
* @return
*/
static int strTransForInt(String str){
int i = -1;
try {
i = Integer.parseInt(str);
}finally {
return i;
}
}
}
// 栈类
class MyStack{
private int size ; // 栈的大小
private int index = -1; // 下标位
private int[] arr; // 栈初始化,因为使用的是数组
/**
* @date 2022/5/16
* @param
*/
public MyStack(){};
public MyStack(int size){
this.size = size;
arr = new int[size];
};
/**
* 判断栈是否是空的
* @return
*/
public boolean isEmpty(){
return index == -1;
}
/**
* 入栈操作
* @param value
*/
public void push(int value){
arr[++index] = value;
}
/**
* 出栈操作
* @return
*/
public void pop(){
if (isEmpty()){
System.out.println("error");
return;
}
System.out.println(arr[index--]);
}
/**
* 查看栈顶是多少
* @return
*/
public void top(){
if (isEmpty()){
System.out.println("error");
return;
}
System.out.println(arr[index]);
}
}
这篇博客展示了如何使用Java实现一个简单的栈数据结构,包括入栈、出栈和查看栈顶元素的操作。示例代码中定义了一个`MyStack`类,并提供了相应的方法来执行这些操作。此外,还包含了一个`strTransForInt`辅助方法用于将字符串转换为整数。
835

被折叠的 条评论
为什么被折叠?



