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 }