-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ12.java
61 lines (55 loc) · 1.59 KB
/
Q12.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
// 12. Design a java program to implement interfaces.
interface IntStack {
void push(int item); //Store an item.
int pop(); //Retrieve an item.
}
class DynStack implements IntStack {
private int stck[];
private int tos;
//Allocate and initialize stack.
DynStack(int size) {
stck = new int[size];
tos = -1;
}
//Push an item onto the stack.
public void push(int item) {
//If stack is full, allocate a larger stack.
if(tos==stck.length-1) {
int temp[] = new int[stck.length * 2];
//Making a double size array.
for(int i=0; i<stck.length; i++)
temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
}
else
stck[++tos] = item;
}
//Pop an item from the stack.
public int pop() {
if(tos < 0)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class Main {
public static void main(String args[]) {
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
//These loops cause each stack to grow.
for(int i=0; i<12; i++)
mystack1.push(i);
for(int i=0; i<20; i++)
mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<12; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<20; i++)
System.out.println(mystack2.pop());
}
}