-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayQueue.java
More file actions
72 lines (65 loc) · 1.82 KB
/
Copy pathArrayQueue.java
File metadata and controls
72 lines (65 loc) · 1.82 KB
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
package pointer;
/**
* @Author: wei1
* @Date: Create in 2018/11/17 21:34
* @Description: 用数组模拟一个队列,通过size来控制有没有满的逻辑很重要
*/
public class ArrayQueue {
private Integer[] arr;
private Integer size;
private Integer first;
private Integer last;
public ArrayQueue(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
size = 0;
first = 0;
last = 0;
}
// 要求实现三个方法
public void push(Integer value) {
if (size.equals(arr.length)) {
throw new IllegalArgumentException("The stack_queue is full");
}
//注意index指向最后一个数前一个
if (last == arr.length - 1) {
arr[last] = value;
last = 0;
} else {
arr[last++] = value;
}
size++;
}
public Integer poll() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
if (first == arr.length - 1) {
int result = arr[first];
first = 0;
size--;
return result;
} else {
size--;
return arr[first++];
}
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[first];
}
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(2);
arrayStack.push(1);
arrayStack.push(2);
// arrayStack.push(1);
System.out.println(arrayStack.peek());
System.out.println(arrayStack.poll());
System.out.println(arrayStack.poll());
// System.out.println(arrayStack.poll());
}
}