-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.java
More file actions
52 lines (41 loc) · 1.15 KB
/
stack.java
File metadata and controls
52 lines (41 loc) · 1.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
public class stack {
// making custom stack in java
public int [] data ; // data should private but to use the Dynamic Stack we make it public
private static final int DIFAULT_SIZE = 10 ;
int ptr = -1 ;
public stack (){
this(DIFAULT_SIZE);
}
public stack (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 boolean isFull(){
return ptr == data.length -1 ;
}
public boolean isEmpty (){
return ptr == -1 ;
}
public int pop () throws Exception {
if (isEmpty()){
throw new Exception ("cannot pop from an emoty stack !!");
}
int removed = data[ptr];
ptr -- ;
return removed ;
}
public int peek () throws Exception{
if (isEmpty()){
throw new Exception (" cannot from an empty stack");
}
return data[ptr];
}
}