-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
132 lines (109 loc) · 1.75 KB
/
stack.cpp
File metadata and controls
132 lines (109 loc) · 1.75 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#define stack_size 10
//Class for stack
class stack
{
int *array;
int top;
int capacity;
public:
stack(int size = stack_size);
~stack();
void push(int);
int pop();
int peek();
int size();
bool is_empty();
bool is_full();
};
//Constructor
stack::stack(int size)
{
array = new int[size];
capacity = size;
top = -1;
}
//Destructor
stack::~stack()
{
delete[] array;
}
//Push
void stack::push(int x)
{
if (is_full())
{
std::cout << "Stack overflow!" << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "Pushed=> " << x << std::endl;
array[++top] = x;
}
//Pop
int stack::pop()
{
if (is_empty())
{
std::cout << "Stack underflow!" << std::endl;
}
std::cout << "Popped=> " << peek() << std::endl;
return array[top--];
}
//Peek
int stack::peek()
{
if (!is_empty())
return array[top];
else
exit(EXIT_FAILURE);
}
//Size
int stack::size()
{
return top + 1;
}
//Check if stack is empty or not
bool stack::is_empty()
{
return top == -1;
//return size() == 0;
}
//Check if stack is full or not
bool stack::is_full()
{
return top == capacity - 1;
//return size() == capacity;
}
int main()
{
int x = 0;
stack st;
x = st.size();
std::cout << "Size=> " << x << std::endl;
st.push(3);
st.push(1);
st.push(12);
st.push(23);
st.push(44);
st.push(53);
st.push(0);
st.push(-1);
st.push(-42);
st.push(0);
st.push(-100);
x = st.peek();
std::cout << "Top=> " << x << std::endl;
st.pop();
st.pop();
if (st.is_empty())
std::cout << "Stack is empty!" << std::endl;
else
std::cout << "Stack is not empty!" << std::endl;
x = st.size();
std::cout << "Size=> " << x << std::endl;
if (st.is_full())
std::cout << "Stack is full!" << std::endl;
else
std::cout << "Stack is not full!" << std::endl;
return 0;
}