forked from thisisshub/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackImplementation.java
More file actions
87 lines (77 loc) · 1.71 KB
/
StackImplementation.java
File metadata and controls
87 lines (77 loc) · 1.71 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
class MyStack
{
int[] arr;
int top;
/* Methods in Stack: push,pop, peek,Empty */
public MyStack(int n)
{
arr = new int[n];
top= -1;
}
public boolean Empty()
{
return (top<0) ;
}
public void push(int data)
{
if(top == arr.length)
{
System.out.println("Stack OverFlow!!");
return ;
}
else
{
top++;
arr[top]=data;
}
}
public int pop() throws Exception
{
if(Empty())
{
throw new Exception("Stack underflow!!");
// System.out.println("Stack UnderFlow!!");
// return 0 ;
}
int poppeddata = arr[top];
top--;
return poppeddata;
}
public int peek()
{
if(Empty())
{
System.out.println("Stack UnderFlow!!");
return 0 ;
}
return arr[top];
}
public void print()
{
for(int i = 0; i<=top;i++)
System.out.print(arr[i]+" ");
}
}
public class StackImplementation {
public static void main(String[] args)
{
MyStack stk = new MyStack(10);
stk.push(3);
stk.push(4);
stk.push(7);
stk.push(9);
try{
System.out.println(stk.pop());
System.out.println(stk.peek());
System.out.println(stk.pop());
System.out.println(stk.pop());
System.out.println(stk.pop());
System.out.println(stk.pop());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
stk.print();
}
}