-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackOP.java
More file actions
99 lines (94 loc) · 2.64 KB
/
StackOP.java
File metadata and controls
99 lines (94 loc) · 2.64 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.Scanner;
public class StackOP {
public static void main(String[] args) {
Stack s = new Stack();
for(;;){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice:-\n1.)Push\n2.)Pop\n3.)Check Stack empty\n4.)Top of Stack\n5.)Display\n0.)Exit ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the element to be pushed:-");
int ele = sc.nextInt();
if(s.push(ele)){
System.out.println("Element "+ele+" pushed successfully");
}
break;
case 2:
s.pop();
break;
case 3:
s.isEmpty();
break;
case 4:
s.top();
break;
case 5:
s.display();
break;
case 0:
System.out.println("Exiting program. Goodbye!");
sc.close();
return;
default:
System.out.println("Invalid choice");
}
}
}
}
class Stack{
int top;
final int size=5;
int[] stack = new int[size];
Stack(){
top=-1;
}
boolean isEmpty(){
if (top<0){
System.out.println("Stack is Empty");
return true;
}else{
System.out.println("Stack is not empty");
return false;
}
}
boolean push(int item){
if(top==size-1){
System.out.println("Stack is full");
return false;
}else{
top++;
stack[top] = item;
return true;
}
}
boolean pop(){
if(isEmpty()){
System.out.println("Stack underflow");
return false;
}else{
System.out.println("Item popped:- "+stack[top--]);
return true;
}
}
boolean top(){
if(isEmpty()){
System.out.println("Stack underflow");
return false;
}else{
System.out.println("Top element:- "+stack[top]);
return true;
}
}
void display(){
if(isEmpty()){
System.out.println("Stack underflow");
}else{
System.out.println("Printing Stack elements...");
for(int i=top;i>=0;i--){
System.out.println(" "+stack[i]+"\n|__|");
}
System.out.println();
}
}
}