-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackUsingArray.java
More file actions
62 lines (52 loc) · 1.41 KB
/
StackUsingArray.java
File metadata and controls
62 lines (52 loc) · 1.41 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
public class StackUsingArray {
private int top = -1;
private int [] arr;
public StackUsingArray (int length){
arr = new int [length];
}
public void push(int data){
if(isFull()){
throw new RuntimeException("Stack is full!!!");
}
top++;
arr[top] = data;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("Stack is Empty!!!");
}
int result = arr[top];
top--;
return result;
}
public int peek(){
if(isEmpty()){
throw new RuntimeException("Stack is Empty!!!");
}
return arr[top];
}
private boolean isEmpty() {
return top < 0;
}
private boolean isFull() {
return arr.length == size();
}
private int size() {
return top+1;
}
public static void main(String [] args){
StackUsingArray sua = new StackUsingArray(3);
sua.push(1);
System.out.println(sua.peek());
sua.push(4);
System.out.println(sua.peek());
sua.push(3);
System.out.println(sua.peek());
System.out.println("POP->"+sua.pop());
System.out.println("Peek->"+sua.peek());
System.out.println("POP->"+sua.pop());
System.out.println("Peek->"+sua.peek());
System.out.println("POP->"+sua.pop());
System.out.println("Peek->"+sua.peek());
}
}