-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackFILO.java
More file actions
83 lines (70 loc) · 2.01 KB
/
Copy pathStackFILO.java
File metadata and controls
83 lines (70 loc) · 2.01 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
public class StackFILO {
private char[] stck;
private int tos;
// Constructor for stack given size.
StackFILO(int size) {
stck = new char[size];
tos = 0;
}
// Constructor for stack given array.
StackFILO(char[] a) {
stck = new char[a.length];
tos = 0;
for (int i = 0; i < a.length; i++) push(a[i]);
}
// Constructor for stack given stack object.
StackFILO(StackFILO obj) {
tos = obj.tos;
stck = new char[obj.stck.length];
for (int i = 0; i < tos; i++) stck[i] = obj.stck[i];
}
void push(char ch) {
if (tos == stck.length) {
System.out.println("The stack is full, try another stack.");
return;
}
stck[tos] = ch;
tos++;
}
char pop() {
if (tos == 0) {
System.out.println("Stack is empty :(");
return (char) 0;
}
tos--;
return stck[tos];
}
}
class FILODemo {
public static void main(String[] args) {
// Construct 10-element empty stack.
StackFILO stk1 = new StackFILO(10);
char[] name = {'T', 'o', 'm'};
// Construct stack from array.
StackFILO stk2 = new StackFILO(name);
char ch;
int i;
// put some characters into stk1.
for (i = 0; i < 10; i++) stk1.push((char) ('A' + i));
// Construct stack from another stack.
StackFILO stk3 = new StackFILO(stk1);
// Show the stacks.
System.out.print("Contents of stk1: ");
for (i = 0; i < 10; i++) {
ch = stk1.pop();
System.out.print(ch);
}
System.out.println("\n");
System.out.print("Contents of stk2: ");
for (i = 0; i < 3; i++) {
ch = stk2.pop();
System.out.print(ch);
}
System.out.println("\n");
System.out.print("Contents of stk3: ");
for (i = 0; i < 10; i++) {
ch = stk3.pop();
System.out.print(ch);
}
}
}