-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23.2.2 (C++) Create a Stack with Constructor & Destructor.cpp
More file actions
100 lines (83 loc) · 1.71 KB
/
23.2.2 (C++) Create a Stack with Constructor & Destructor.cpp
File metadata and controls
100 lines (83 loc) · 1.71 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
/// Create a Stack with constructor & destructor
#include <iostream>
#include <stdio.h>
using namespace std;
#define SIZE 10
class stack
{
char stck[SIZE]; // holds the stack
int tos; // index of top of stack
public:
stack(); // Constructor
~stack(); // Destructor
void push(char ch); // push character on stack
char pop(); // pop character from stack
};
// Initialize the stack
stack :: stack()
{
cout<<" Constructing a stack... \n";
tos=0;
}
stack :: ~stack()
{
cout<<" Destructing a stack... \n";
}
// Push a character
void stack :: push(char ch)
{
if (tos==SIZE)
{
cout<<" Stack is full \n";
return;
}
stck[tos] = ch;
tos++;
}
// Pop a character
char stack :: pop()
{
if(tos==0)
{
cout<<" Stack is Empty \n";
return 0; // return null on empty stack
}
tos--;
return stck[tos];
}
int main()
{
// Create two stacks that are automatically initialized
stack s1, s2;
int i;
s1.push('a');
s2.push('x');
s1.push('b');
s2.push('y');
s1.push('c');
s2.push('z');
for(i=0; i<3; i++)
{
cout<<" Pop s1: "<<s1.pop()<<" \n";
}
for(i=0; i<3; i++)
{
cout<<" Pop s2: "<<s2.pop()<<" \n";
}
return 0;
}
/* ===== Output/Result:
Input:___________________
(Initialization values within a program code)
Output:_________________
Constructing a stack...
Constructing a stack...
Pop s1: c
Pop s1: b
Pop s1: a
Pop s2: z
Pop s2: y
Pop s2: x
Destructing a stack...
Destructing a stack...
*/