-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStackv1.java
100 lines (80 loc) · 1.94 KB
/
Stackv1.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
interface stack1 {
void push(char item);
char pop();
}
class StackC implements stack1 {
private char[] stk;
private int tos;
StackC(int size) {
stk = new char[size];
tos = -1;
}
public void push(char item) {
if (tos == stk.length - 1) {
System.out.println("Stack Overflows");
char t[] = new char[stk.length * 2];
for (int i = 0; i < stk.length; i++)
t[i] = stk[i];
stk = t;
stk[++tos] = item;
} else
stk[++tos] = item;
}
public char pop() {
if (tos < 0) {
System.out.println("Stack Underflows");
return '0';
} else
return stk[tos--];
}
}
interface stack2 {
void push(String item);
String pop();
}
class StackS implements stack2 {
private String[] stk;
private int tos;
StackS(int size) {
stk = new String[size];
tos = -1;
}
public void push(String item) {
if (tos == stk.length - 1) {
System.out.println("Stack Overflows");
String t[] = new String[stk.length * 2];
for (int i = 0; i < stk.length; i++)
t[i] = stk[i];
stk = t;
stk[++tos] = item;
} else
stk[++tos] = item;
}
public String pop() {
if (tos < 0) {
System.out.println("Stack Underflows");
return "0";
} else
return stk[tos--];
}
}
class Run2 {
public static void main(String[] args) {
stack1 charInf;
stack2 stringInf;
StackC chSTK = new StackC(3);
StackS stringSTK = new StackS(3);
charInf = chSTK;
for (int i = 0; i < 3; i++)
charInf.push('A');
System.out.println("Char Stack Contents using interface reference: ");
for (int i = 0; i < 3; i++)
System.out.println(charInf.pop());
stringInf = stringSTK;
for (int i = 0; i < 3; i++)
stringInf.push("I don't like Java anymore");
System.out.println("String Stack Contents using interface reference: ");
for (int i = 0; i < 3; i++)
System.out.println(stringInf.pop());
}
}