Java数组模拟栈

一、概述

  注意:模拟战还可以用链表

 

  

   

   

 

二、代码

  

 1 public class ArrayStack {
 2     @Test
 3     public void test() {
 4         Stack s = new Stack(5);
 5 
 6         s.push(1);
 7         s.push(2);
 8         s.push(3);
 9         s.push(4);
10         s.push(5);
11         s.push(6);
12         s.printStack();
13         /*System.out.println("------------------------");
14         s.pop();
15         s.pop();
16         s.pop();
17         s.pop();
18         s.pop();
19         s.pop();
20         s.printStack();*/
21     }
22 }
23 
24 class Stack {
25     //栈的最大容量
26     static int maxSize;
27     //用数组模拟
28     static int[] arr;
29     //栈顶,默认-1
30     static int top = -1;
31 
32     public Stack(int maxSize) {
33         this.maxSize = maxSize;
34         //创建数组
35         arr = new int[this.maxSize];
36     }
37 
38     public static boolean isEmpty() {
39         return top == -1;
40     }
41 
42     public static boolean isFull() {
43         return top == maxSize - 1;
44     }
45 
46     public static void push(int value) {
47         if (isFull()) {
48             System.out.println("栈已满");
49             return;
50         }
51         arr[++top] = value;
52     }
53 
54     public static int pop() {
55         if (isEmpty()) {
56             System.out.println("栈已空");
57             return -1;
58         }
59         int tmp = arr[top];
60         arr[top] = 0;
61         top--;
62         return tmp;
63     }
64 
65     public static void printStack() {
66         for (int i = top; i >=0 ; i--) {
67             System.out.println(arr[i]);
68         }
69     }
70 
71 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值