-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathImplementStack.java
More file actions
61 lines (54 loc) · 1.48 KB
/
ImplementStack.java
File metadata and controls
61 lines (54 loc) · 1.48 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
class Stack {
private int top = -1;
private int size = 16;
private int initial_size = 16;
private int[] stackArray = new int[initial_size];
//constructor
Stack(){
this.top = -1;
this.stackArray = new int[initial_size];
this.size = 0;
}
// Push a new item into the stack
public void push(int x) {
// Write your code here
if (size == Math.pow(2,32) - 1) {
throw new NoSuchElementException();
}
if (size < initial_size) {
top++;
stackArray[top] = x;
size++;
} else {
initial_size = initial_size * 2;
int[] stackArrayNew = new int[initial_size];
for(int i = 0; i < this.stackArray.length; i++) {
stackArrayNew[i] = stackArray[i];
}
this.stackArray = stackArrayNew;
top++;
stackArray[top] = x;
size++;
}
}
// Pop the top of the stack
public void pop() {
// Write your code here
if (!isEmpty()) {
stackArray[top] = 0;
top--;
} else {
throw new NoSuchElementException();
}
}
// Return the top of the stack
public int top() {
// Write your code here
return stackArray[top];
}
// Check the stack is empty or not.
public boolean isEmpty() {
// Write your code here
return (top == -1);
}
}