JAVA用数组模拟栈(记录)
前言
用数组模拟栈
栈是后进先出
比链表简单好多φ(゜▽゜*)♪
练习之路☞acwing
一、创建栈
class arrayStack{
int size;//栈的大小
int[] stack;// 数据放在数组中
int top=-1;//栈顶,初始值为-1
public arrayStack(int size) {
this.size = size;
stack=new int[this.size];
}
}
二、栈的方法
//判断栈满
public boolean isFull(){
return top==size-1;
}
//判断栈空
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(int value){
//永远都要先判断是否栈满
if (isFull()){
System.out.println("栈满,不能存数据哦");
return;
}
top++;//相当于指针,指到哪里数据存到哪里
stack[top]=value;
}
//出栈
public int pop(){
if (isEmpty()){
// System.out.println("栈空,里面没有数据哦");
// 抛出异常
throw new RuntimeException("栈空,没有数据");
}
int value=stack[top];
top--;
return value;
}
//遍历栈
public void show(){
if (isEmpty()){
System.out.println("里面没有数据啦");
}
for (int x:stack) {
System.out.println(x);
}
}
//查询栈顶元素
public void showTop(){
if(isEmpty()){
System.out.println("无数据");
return;
}
System.out.println(stack[0]);
}
三、整体代码
package Second;
import java.util.Scanner;
/*
用数组模拟栈
栈是后进先出
*/
public class Stack828 {
static int N=10010;
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
arrayStack arraystack=new arrayStack(10);
int M=scanner.nextInt();
while(M-->0){
String commend=scanner.next();
switch (commend){
case "push" :
int x=scanner.nextInt();
arraystack.push(x);
break;
case "pop":
try {
arraystack.pop();
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case "empty":
arraystack.isEmpty();
break;
case "query":
arraystack.showTop();
}
}
}
}
//用数组定义栈
class arrayStack{
int size;//栈的大小
int[] stack;// 数据放在数组中
int top=-1;//栈顶,初始值为-1
public arrayStack(int size) {
this.size = size;
stack=new int[this.size];
}
//判断栈满
public boolean isFull(){
return top==size-1;
}
//判断栈空
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(int value){
//永远都要先判断是否栈满
if (isFull()){
System.out.println("栈满,不能存数据哦");
return;
}
top++;//相当于指针,指到哪里数据存到哪里
stack[top]=value;
}
//出栈
public int pop(){
if (isEmpty()){
// System.out.println("栈空,里面没有数据哦");
// 抛出异常
throw new RuntimeException("栈空,没有数据");
}
int value=stack[top];
top--;
return value;
}
//遍历栈
public void show(){
if (isEmpty()){
System.out.println("里面没有数据啦");
}
for (int x:stack) {
System.out.println(x);
}
}
//查询栈顶元素
public void showTop(){
if(isEmpty()){
System.out.println("无数据");
return;
}
System.out.println(stack[top]);
}
}
四、总结
弹出数据和加入数据都比直接写链表简单,抛出异常必不可少,如果不需要判断栈满,其实可以不用写栈的大小。