-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
executable file
·83 lines (74 loc) · 1.49 KB
/
Stack.java
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
/*
Lab 1 : implementation of Stack
*/
import java.util.*;
public class Stack {
private int[] s;
private int maxsize,top;
public Stack(int maxsize){
this.maxsize=maxsize;
this.s = new int[maxsize];
this.top=0;
}
public boolean isEmpty(){
return this.top==0;
}
public void push(int element) throws Exception{
if(this.top == this.maxsize){
Exception e=new Exception("Stack Overflow");
throw e;
}
else{
this.s[top]=element;
this.top++;
}
}
public int pop() throws Exception{
if(this.top == 0){
Exception e=new Exception("Stack Underflow");
throw e;
}
else{
this.top--;
return this.s[this.top];
}
}
public static void main(String[] args) {
int choice,temp;
Scanner in = new Scanner(System.in);
System.out.print(" Enter max stack size : ");
temp=in.nextInt();
Stack s = new Stack(temp);
System.out.print("\n 1. Push\n 2. Pop\n 3. CheckEmpty\n 4. Exit \n\n ");
do{
System.out.print("\nEnter Choice : ");
choice=in.nextInt();
if(choice==1){
System.out.print(" \t\t Enter element : ");
temp = in.nextInt();
try{
s.push(temp);
}
catch(Exception e){
e.printStackTrace();
}
}
else if (choice==2){
try{
System.out.println(" \t\t Popped "+ s.pop());
}
catch( Exception e){
e.printStackTrace();
}
}
else if(choice==3)
{
if(s.isEmpty())
System.out.println(" Yes ");
else
System.out.println(" No ");
}
}
while(choice!=4);
}
}