1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| package dsa.structure.ds105_stack;
import java.util.Arrays;
public class MyArrayStack { private int capacity; private int top = -1; private String[] table;
public MyArrayStack(int capacity) { this.capacity = capacity; this.table = new String[capacity]; }
public boolean isEmpty() { return top == -1; }
public boolean isFull() { return top == capacity - 1; }
public boolean push(String s) { if (isFull()) { return false; }
table[top + 1] = s; top++;
return true; }
public String pop() { if (isEmpty()) { return null; }
String v = table[top]; table[top] = null; top--;
return v; }
public String toString() { return Arrays.toString(table); }
public static void main(String[] args) { int capacity = 7; MyArrayStack stack = new MyArrayStack(capacity);
System.out.println("\n---test push---\n"); for (int i = 0; i < capacity + 1; i++) { String s = "" + i;
boolean ok = stack.push(s); if (ok) { System.out.println(String.format("push value %2s , stack is %s", s, stack.toString())); } else { System.out.println("stack is full"); break; } }
System.out.println("\n---test pop and push---\n"); for (int i = 0; i < capacity + 2; i++) { String s = "" + (i + capacity);
if (i < capacity / 2) { s = stack.pop(); System.out.println(String.format("pop value %2s , stack is %s", s, stack.toString())); } else { boolean ok = stack.push(s); if (ok) { System.out.println(String.format("push value %2s , stack is %s", s, stack.toString())); } else { System.out.println("stack is full"); break; } } }
System.out.println("\n---test pop---\n"); while (true) { String s = stack.pop(); if (s != null) { System.out.println(String.format("pop value %2s , stack is %s", s, stack.toString())); } else { System.out.println("stack is empty"); break; } } } }
|