1 package my_basic.class_3;
2
3 /**
4 * 用数组结构实现大小固定的队列和栈
5 */
6 public class Code_01_Array_stack_queue {
7
8 public static class ArrayStack{
9 private Integer[] arr;
10 private Integer size;
11
12 public ArrayStack(int initSize) {
13 if (initSize < 0) {
14 throw new IllegalArgumentException("The init size is less than 0");
15 }
16 arr = new Integer[initSize];
17 size=0;
18
19 }
20
21 public Integer peek() {
22 if (size == 0) {
23 return null;
24 }
25 return arr[size-1];
26
27 }
28 public void push(int num) {
29 if (size == arr.length) {
30 throw new ArrayIndexOutOfBoundsException("the stack is full");
31 }
32 arr[size++] = num;
33 }
34 public Integer pop() {
35 if (size == 0) {
36 throw new ArrayIndexOutOfBoundsException("the stack is empty");
37 }
38 size--;
39 return arr[size];
40 }
41
42 }
43
44 public static class ArrayQueue{
45 private Integer[] arr;
46 private int size;
47 private int first;
48 private int last;
49
50 public ArrayQueue(int initSize) {
51 if (initSize < 0 ) {
52 throw new IllegalArgumentException("The init size is less than 0");
53 }
54 arr = new Integer[initSize];
55 size=0;
56 first=0;
57 last=0;
58 }
59 public Integer peek() {
60 if (size == 0) {
61 return null;
62 }
63 return arr[first];
64 }
65 public void push(int obj) {
66 if (size == arr.length) {
67 throw new ArrayIndexOutOfBoundsException("the queue is full");
68 }
69 size++;
70 arr[last] = obj;
71 last = (last == arr.length-1) ? 0 : last++;
72 }
73 public Integer poll() {
74 if (size == 0) {
75 throw new ArrayIndexOutOfBoundsException("the queue is empty");
76 }
77 size--;
78 int res = first;
79 first = (first == arr.length-1)? 0 : first++;
80 return arr[res];
81 }
82
83 }
84
85 public static void main(String[] args) {
86
87
88 }
89
90
91 }