-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyStack.java
86 lines (72 loc) · 1.52 KB
/
MyStack.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
84
85
class MyStack implements StackInterface
{
int capacity=1;
Object [ ] A=new Object[capacity];
int t=0;
// Addig element to the stack and when array gets full just expand it
public void push (Object o)
{
if(t==capacity)
expand();
if(o!=null)
A[t++]=o;
}
private void expand() // Method for expand the array with double size
{
int length= t;
Object B[ ]= new Object[capacity*2];
for(int i=0;i<length;i++)
B[i]=A[i];
A=B;
capacity=capacity*2;
}
//Method pop to delete last element in stack return that element
public Object pop() throws EmptyStackException
{
;
if(isEmpty())
{
EmptyStackException e= new EmptyStackException();
throw e;
}
else {
return A[--t];
}
}
// method top to see uppermost element of stack
public Object top() throws EmptyStackException
{
if( isEmpty()) // Checking whether stack is empty or not
{
EmptyStackException e =new EmptyStackException();
throw e;
}
else
{
return A[t-1];
}
}
//isEmpty method to check the given stack is empty or not
public boolean isEmpty()
{
return t==0;
}
// toString method to convert given data into string
public String toString()
{
String sb = ("[");
for(int i=t-1;i>=0;i--)
{
sb+=(A[i]);
sb+=(i==0?"":", ");
}
sb+=("]");
return sb;
}
}
class EmptyStackException extends Exception
{
EmptyStackException(){
super();
}
}