-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.java
More file actions
97 lines (91 loc) · 3.05 KB
/
stack.java
File metadata and controls
97 lines (91 loc) · 3.05 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
import java.util.Scanner;
class StackOverflowException extends Exception{
private static final long serialVersionUID = 1L;
StackOverflowException(String s) {
super(s);
}
}
class StackUnderflowException extends Exception{
private static final long serialVersionUID = 1L;
StackUnderflowException(String s) {
super(s);
}
}
class Stack{
int stackSize,top=-1;
int[] arr;
Stack(int stackSize){
this.stackSize=stackSize;
arr = new int[stackSize];
}
public void push(int element) throws StackOverflowException {
if(top>=stackSize-1)
throw new StackOverflowException("Stack OverFlow Occured");
else
arr[++top] = element;
}
public int pop() throws StackUnderflowException{
if(top==-1)
throw new StackUnderflowException("Stack UnderFlow Occured\n");
else
return arr[top--];
}
public void peek() throws StackUnderflowException{
if(top==-1)
throw new StackUnderflowException("Stack UnderFlow Occured\n");
else
System.out.println(arr[top]+" top of Stack\n");
}
}
public class stack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the stack: ");
int size = sc.nextInt();
Stack S = new Stack(size);
boolean flag=true;
System.out.println(" 1 to push");
System.out.println("2 to Pop");
System.out.println(" 3 to Peek");
System.out.println(" 4 to Exit");
while(flag){
System.out.print("\nChocie: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter a number to push into the stack: ");
int num = sc.nextInt();
try{
S.push(num);
}
catch(StackOverflowException e){
System.out.println("Exception "+e);
}
break;
case 2:
try{
System.out.println(S.pop()+" poped out ");
}
catch(StackUnderflowException e){
System.out.println("Exception Occured: "+e);
}
break;
case 3:
try{
S.peek();
}
catch(StackUnderflowException e){
System.out.println("Exception Occured: "+e);
}
break;
case 4:
System.out.println("Exiting...\n");
flag=false;
break;
default:
System.out.println("Wrong Chocie!! Please Enter again");
}
}
sc.close();
}
}