-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleStackDemo2.0.java
More file actions
104 lines (73 loc) · 1.78 KB
/
SimpleStackDemo2.0.java
File metadata and controls
104 lines (73 loc) · 1.78 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class SimpleStackDemo {
public static void main(String[] args){
int i;
char ch;
System.out.println("Demonstrate SimpleStack\n");
// Construct 10-element empty stack.
SimpleStack stack = new SimpleStack(10);
System.out.println("\nPush 10 items onto a 10-element stack.");
//Push the letters Althrouh J onto the stack
System.out.println("Pushing: ");
for (ch = 'A'; ch < 'K'; ch++)
{
System.out.print(ch+" ");
stack.push(ch);
}
System.out.print("\nPop those 10 items from stack.");
//pop
System.out.println("Poping: " );
for(i = 0; i < 10; i++){
ch = stack.pop();
System.out.print(ch+" ");
}
System.out.println("\nNext, use isempty and isfull");
//Push the letters until the stack is full
System.out.print("Pushing: ");
for(ch = 'A'; !stack.isFull(); ch++){
System.out.print(ch+" " );
stack.push(ch);
}
System.out.println("\n");
//Pop
System.out.print("Popping: ");
while(!stack.isEmpty())
{
ch = stack.pop();
System.out.print(ch+" ");
}
}
}
class SimpleStack{
private char[] data;
private int tos;
//Constuct an empty stack given its size
SimpleStack(int size) {
data = new char[size]; // create the array to hold the stack
tos = 0;
}
// Push
void push(final char ch) {
if (isFull()) {
System.out.print(" -- Stack is full.");
return;
}
data[tos] = ch;
tos++;
}
// Pop
char pop() {
if (isEmpty()) {
System.out.print(" -- Stack is empty.");
return (char) 0;
}
tos--;
return data[tos];
}
// isEmpty
boolean isEmpty() {
return tos == 0;
}
boolean isFull() {
return tos == data.length;
}
}