0
|
1 package example2;
|
|
2
|
|
3 public class MyStack {
|
|
4 private Object[] stack;
|
|
5 private int size = 0;
|
|
6 private static final int MAX_SIZE = 16;
|
|
7
|
|
8 public MyStack() {
|
|
9 this.stack = new Object[MAX_SIZE];
|
|
10 }
|
|
11
|
|
12 public void push(Object e) {
|
|
13 if (size==MAX_SIZE) return;
|
|
14 stack[size++] = e;
|
|
15 }
|
|
16
|
|
17 public Object pop() {
|
|
18 if (size == 0) {
|
|
19 return null;
|
|
20 }
|
|
21 return stack[--size];
|
|
22 }
|
|
23
|
|
24 private void print() {
|
|
25 for (Object o : this.stack) {
|
|
26 if (o == null) {
|
|
27 System.out.print("n ");
|
|
28 } else {
|
|
29 System.out.print(o + " ");
|
|
30 }
|
|
31 }
|
|
32 System.out.println();
|
|
33 }
|
|
34
|
|
35 public static void main(String[] args) {
|
|
36 MyStack s = new MyStack();
|
|
37
|
|
38 System.out.print("First:");
|
|
39 s.print();
|
|
40
|
|
41 for (int i = 0; i < 10; i++) {
|
|
42 s.push(Integer.valueOf(i)); // push
|
|
43 }
|
|
44
|
|
45 System.out.print("push: ");
|
|
46 s.print();
|
|
47
|
|
48 for (int i = 0; i < 10; i++) {
|
|
49 s.pop();
|
|
50 }
|
|
51
|
|
52 System.out.print("pop: ");
|
|
53 s.print();
|
|
54 }
|
|
55 } |