-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
78 lines (66 loc) · 1.73 KB
/
Stack.java
File metadata and controls
78 lines (66 loc) · 1.73 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
class Stack{
int max_size;
int array[];
int top;
public Stack(int max_size){
this.max_size = max_size;
array = new int[max_size];
this.top = -1;
}
public boolean isEmpty(){
return top == -1;
}
public boolean isFull(){
return top == max_size-1;
}
public void push(int data){
if(isFull()){
System.out.println("Stack is full!, Cannot insert an element");
}else{
array[++top] = data;
}
}
public int pop(){
if(isEmpty()){
System.out.println("Stack is Empty!, Cannot remove an element");
return -1;
}
else{
return array[top--];
}
}
public int peek(){
if(isEmpty()){
System.out.println("Stack is Empty");
return -1;
}
else{
return array[top];
}
}
public void display(){
if(isEmpty()){
System.out.println("Stack is Empty");
}
for(int a=top; a>=0; a--){
System.out.print(array[a] + " ");
}
System.out.println();
}
public static void main(String[] args){
Stack stack1 = new Stack(5);
System.out.println(stack1.isEmpty());
System.out.println(stack1.isFull());
stack1.push(10);
stack1.push(15);
stack1.push(5);
stack1.push(35);
System.out.print("After push : ");
stack1.display();
stack1.pop();
stack1.pop();
System.out.print("After pop : ");
stack1.display();
System.out.println("Peek is " + stack1.peek());
}
}