Repository navigation
Expand file tree
/
Copy pathStackArray.java
More file actions
80 lines (61 loc) · 1.62 KB
/
Copy pathStackArray.java
File metadata and controls
80 lines (61 loc) · 1.62 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
package DSA.Stack;
import java.util.EmptyStackException;
public class StackArray {
private int[] stack;
private int top;
private Object lock;
public StackArray(int capacity) {
this.stack = new int[capacity];
this.top = -1;
this.lock = new Object();
}
public boolean isEmpty() {
return this.top < 0;
}
private void push(int value) {
synchronized (lock) {
if (this.top + 1 == this.stack.length) {
throw new RuntimeException("stack is full");
}
this.top++;
this.stack[this.top] = value;
}
}
private int pop() {
synchronized (new Object()) {
if (isEmpty()) {
throw new EmptyStackException();
}
int result = this.stack[this.top];
this.stack[this.top] = Integer.MAX_VALUE;
this.top--;
return result;
}
}
public int peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return this.stack[this.top];
}
private void printStack() {
if (isEmpty()) {
throw new EmptyStackException();
}
for (int i = this.top; i > 0; i--) {
System.out.println(this.stack[i]);
}
}
public static void main(String[] args) {
StackArray ll = new StackArray(6);
ll.push(1);
ll.push(2);
ll.push(3);
ll.push(5);
ll.push(6);
ll.push(7);
ll.printStack();
System.out.println("pop: " + ll.pop());
ll.printStack();
}
}