|
8 | 8 | * of an array implementation of a Stack. So an element can only be added/removed |
9 | 9 | * from the end of the array. In theory stack have no fixed size, but with an |
10 | 10 | * array implementation it does. |
11 | | - * |
12 | | - * @author Unknown |
13 | 11 | */ |
14 | 12 | public class StackArray { |
15 | 13 |
|
16 | 14 | /** |
17 | | - * Main method |
18 | | - * |
19 | | - * @param args Command line arguments |
| 15 | + * Driver Code |
20 | 16 | */ |
21 | 17 | public static void main(String[] args) { |
22 | 18 | // Declare a stack of maximum size 4 |
23 | 19 | StackArray myStackArray = new StackArray(4); |
24 | 20 |
|
| 21 | + assert myStackArray.isEmpty(); |
| 22 | + assert !myStackArray.isFull(); |
| 23 | + |
25 | 24 | // Populate the stack |
26 | 25 | myStackArray.push(5); |
27 | 26 | myStackArray.push(8); |
28 | 27 | myStackArray.push(2); |
29 | 28 | myStackArray.push(9); |
30 | 29 |
|
31 | | - System.out.println("*********************Stack Array Implementation*********************"); |
32 | | - System.out.println(myStackArray.isEmpty()); // will print false |
33 | | - System.out.println(myStackArray.isFull()); // will print true |
34 | | - System.out.println(myStackArray.peek()); // will print 9 |
35 | | - System.out.println(myStackArray.pop()); // will print 9 |
36 | | - System.out.println(myStackArray.peek()); // will print 2 |
| 30 | + assert !myStackArray.isEmpty(); |
| 31 | + assert myStackArray.isFull(); |
| 32 | + assert myStackArray.peek() == 9; |
| 33 | + assert myStackArray.pop() == 9; |
| 34 | + assert myStackArray.peek() == 2; |
| 35 | + assert myStackArray.size() == 3; |
37 | 36 | } |
38 | 37 |
|
39 | 38 | /** |
@@ -62,7 +61,7 @@ public static void main(String[] args) { |
62 | 61 | public StackArray() { |
63 | 62 | this(DEFAULT_CAPACITY); |
64 | 63 | } |
65 | | - |
| 64 | + |
66 | 65 | /** |
67 | 66 | * Constructor |
68 | 67 | * |
@@ -162,4 +161,13 @@ public boolean isFull() { |
162 | 161 | public void makeEmpty() { // Doesn't delete elements in the array but if you call |
163 | 162 | top = -1; // push method after calling makeEmpty it will overwrite previous values |
164 | 163 | } |
| 164 | + |
| 165 | + /** |
| 166 | + * Return size of stack |
| 167 | + * |
| 168 | + * @return size of stack |
| 169 | + */ |
| 170 | + public int size() { |
| 171 | + return top + 1; |
| 172 | + } |
165 | 173 | } |
0 commit comments