



package com.chb.Stack;
public class testStack {
public static void main(String[] args) {
ArrayStack stack=new ArrayStack(10);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.show();
System.out.println(stack.peek());
stack.pop();
stack.show();
}
}
class ArrayStack{
private int maxSize;//栈的大小
private int[]stack;
private int top=-1;
public ArrayStack(int maxSize) {
super();
this.maxSize = maxSize;
stack =new int[maxSize];
}
//栈满
public boolean isFull() {
return top==maxSize-1;
}
//栈空
public boolean isEmpty() {
return top==-1;
}
//入栈
public void push(int n) {
if(isFull()) {
System.out.println("栈满");
return;
}
stack[++top]=n;
}
//出栈
public int pop() {
if(isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
return stack[top--];
}
//取栈顶元素
public int peek() {
return stack[top];
}
//遍历栈
public void show() {
if(isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
for (int i = top; i >=0; i--) {
System.out.print(stack[i]+" ");
}
System.out.println();
}
}
运行结果:

本文深入讲解了使用Java实现栈的基本操作,包括入栈、出栈、查看栈顶元素及遍历栈内所有元素。通过具体代码示例,展示了如何创建并操作一个数组实现的栈,适合初学者理解和掌握栈这一数据结构。
2101

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



