-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_To_Stack_Queue.java
More file actions
84 lines (71 loc) · 2.15 KB
/
Copy pathArray_To_Stack_Queue.java
File metadata and controls
84 lines (71 loc) · 2.15 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
73
74
75
76
77
78
79
80
81
82
83
84
public class Array_To_Stack_Queue {
public static class ArrayStack {
private Integer[] arr;
private Integer size;
public ArrayStack(int initsize) {
if (initsize < 0) {
throw new IllegalArgumentException("The init size is less than 0!");
}
arr = new Integer[initsize];
size = 0;
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[size - 1];
}
public void push(int obj) {
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("The stack is full!");
}
arr[size++] = obj;
}
public Integer pop() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The stack is empty!");
}
return arr[--size];
}
}
public static class ArrayQueue {
private Integer[] arr;
private Integer size;
private Integer first;
private Integer last;
public ArrayQueue(int initsize) {
if (initsize < 0) {
throw new IllegalArgumentException("Initial size is less than 0!");
}
arr = new Integer[initsize];
size = 0;
first = 0;
last = 0;
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[first];
}
public void push(int obj) {
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full!");
}
size++;
arr[last] = obj;
last = last == arr.length - 1 ? 0 : last + 1;
}
public Integer poll() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("THe queue is empty!");
}
size--;
index = first;
first = fist = arr.length - 1 ? 0 : first + 1;
return arr[index];
}
}
public static void main(String[] args) {
}
}