📄 mystack.java
字号:
package exec.day0911;
/**
* 写一个类用来模拟栈这种数据结构,要求底层使用数组存储数据,
* 并给出相应的进栈和出栈的方法
* @author Administrator
*
*/
public class MyStack {
int arr[];
int count;
public MyStack(int size){
arr = new int[size];
}
public void push(int n){
if(count==arr.length){
System.out.println("添加元素"+n+"失败,栈空间已满,不能再添加元素!");
return;
}
arr[count++] = n;
}
public int pop(){
if(count==0){
System.out.println("栈为空,不能取出元素!");
return -1;
}
int num = arr[--count];
System.out.println("取出元素"+num);
return num;
}
public void print(){
System.out.print("[");
for(int i=0;i<count;i++){
System.out.print(arr[i] +" ");
}
System.out.println("]");
}
/**
* @param args
*/
public static void main(String[] args) {
MyStack ms = new MyStack(6);
ms.push(10);
ms.push(20);
ms.push(5);
ms.push(1);
ms.push(8);
ms.push(19);
ms.push(200);
ms.print();
ms.pop();
ms.pop();
ms.pop();
ms.print();
ms.push(100);
ms.print();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -