forked from Anjalijha12345/DSA--Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomStack.java
More file actions
49 lines (41 loc) · 1.07 KB
/
CustomStack.java
File metadata and controls
49 lines (41 loc) · 1.07 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
package saikat;
public class CustomStack {
protected int[] data;
private static final int DEFAULT_SIZE = 10;
int ptr = -1;
public CustomStack() {
this(DEFAULT_SIZE);
}
public CustomStack(int size) {
this.data = new int[size];
}
public boolean push(int item){
if(isFull()){
System.out.println("Stack is Full");
return false;
}
ptr++;
data[ptr] = item;
return true;
}
public int pop() throws Exception {
if (isEmpty()){
throw new Exception("cannot pop from an empty stack");
}
int removed = data[ptr];
ptr--;
return removed;
}
public int peek() throws Exception{
if (isEmpty()){
throw new Exception("cannot pop from an empty stack");
}
return data[ptr];
}
public boolean isFull() {
return ptr == data.length-1; //pointer is at last index
}
public boolean isEmpty() {
return ptr == -1;
}
}