当前位置:网站首页>如何用数组模拟栈(超简易代码)
如何用数组模拟栈(超简易代码)
2022-07-21 05:16:00 【weixin_46685039】
/**
* 用数组模拟栈
*/
public class MyStack1 {
private int[] arr;
private int maxSize;
private int top; // 栈 顶的位置
public MyStack1(int maxSize){
this.maxSize=maxSize;
arr=new int[maxSize];
top=-1;
}
// 显示栈中的所有数据
public void display(){
for(int i=top;i>=0;i--){
System.out.print(arr[i]+" ");
}
System.out.println();
}
// 压入数据
public void push(int value){
if(top==maxSize-1){
System.out.println("栈已满 不能存入");
return;
}
if(top<maxSize-1){
arr[++top]=value;
}
}
// 弹出数据
public int pop(){
// 判断栈是否为空
if(top==-1){
System.out.println("栈为null栈 不能弹出");
throw new RuntimeException("栈为null栈 不能弹出");
}
return arr[top--];
}
// 判断是否为null栈
public boolean isEmpty(){
return top==-1;
}
// 判断是否为满栈
public boolean isFull(){
return top==maxSize-1;
}
// 栈置为null栈
public void makeNull(){
top=-1;
}
public static void main(String[] args) {
MyStack1 stack = new MyStack1(4);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.display();
stack.push(5);
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
}
}
边栏推荐
- 004:打印字符
- 19. Delete the penultimate node of the linked list
- 14. 最长公共前缀
- 概率论-最大似然估计
- XML详解
- Heap - principle to application - heap sorting, priority queue
- Subsequence
- 567. Arrangement of strings
- Programmation créative / groupe primaire (4e - 6e année) - graphisme créatif
- This Bluetooth chip giant aims at the WiFi SOC market and launches a low-power WiFi MCU product line
猜你喜欢
Do you think sub database and sub table are really suitable for your system? Talk about how to select sub databases, sub tables and newsql
543. 二叉树的直径
74. Search two-dimensional matrix
01 knapsack interview questions series (I)
14. 最长公共前缀
Heap - principle to application - heap sorting, priority queue
328. 奇偶链表
299. 猜数字游戏
The evolution of data warehouse in recent 10 years and suggestions on database learning
Using UUID as MySQL primary key, my boss broke up
随机推荐
datart 数据可视化作品开源 | 图表插件作品全开源啦,通过百度云下载链接提取
543. 二叉树的直径
108. 将有序数组转换为二叉搜索树
What is a direct drinking machine? What is its working principle and advantages?
226. 翻转二叉树
D - AND and SUM (AtCoder Beginner Contest 238)
堆-原理到应用——堆排序、优先级队列
Common shortcut keys of robotframework
Do you think sub database and sub table are really suitable for your system? Talk about how to select sub databases, sub tables and newsql
第九周ACM训练报告
Built in WiFi and Bluetooth chip of Flathead brother xuantie
How to complete the design of RGB lamp Bluetooth mesh module from 0 to 1
The robotframework (ride) keyword cannot be used or the keyword is black
567. Arrangement of strings
火爆社区的开源数据可视化工具 datart 新用户体验教程
230. 二叉搜索树中第K小的元素
What are the characteristics and application fields of Bluetooth module in the Internet of things?
卡牌
快速排序
2021普及组总结