Skip to content

Commit 6c2a2c4

Browse files
committed
Create stack.cpp
1 parent 990fdb8 commit 6c2a2c4

File tree

1 file changed

+132
-0
lines changed

1 file changed

+132
-0
lines changed

stack.cpp

+132
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#include <iostream>
2+
3+
#define stack_size 10
4+
5+
//Class for stack
6+
7+
class stack
8+
{
9+
int *array;
10+
int top;
11+
int capacity;
12+
13+
public:
14+
stack(int size = stack_size);
15+
~stack();
16+
17+
void push(int);
18+
int pop();
19+
int peek();
20+
int size();
21+
bool is_empty();
22+
bool is_full();
23+
};
24+
25+
//Constructor
26+
stack::stack(int size)
27+
{
28+
array = new int[size];
29+
capacity = size;
30+
top = -1;
31+
}
32+
33+
//Destructor
34+
stack::~stack()
35+
{
36+
delete[] array;
37+
}
38+
39+
//Push
40+
void stack::push(int x)
41+
{
42+
if (is_full())
43+
{
44+
std::cout << "Stack overflow" << std::endl;
45+
exit(EXIT_FAILURE);
46+
}
47+
std::cout << "Pushed=> " << x << std::endl;
48+
array[++top] = x;
49+
}
50+
51+
//Pop
52+
int stack::pop()
53+
{
54+
if (is_empty())
55+
{
56+
std::cout << "Stack underflow" << std::endl;
57+
}
58+
std::cout << "Popped=> " << peek() << std::endl;
59+
return array[top--];
60+
}
61+
62+
//Peek
63+
int stack::peek()
64+
{
65+
if (!is_empty())
66+
return array[top];
67+
else
68+
exit(EXIT_FAILURE);
69+
}
70+
71+
//Size
72+
int stack::size()
73+
{
74+
return top + 1;
75+
}
76+
77+
//Check if stack is empty or not
78+
bool stack::is_empty()
79+
{
80+
return top == -1;
81+
//return size() == 0;
82+
}
83+
84+
//Check if stack is full or not
85+
bool stack::is_full()
86+
{
87+
return top == capacity - 1;
88+
//return size() == capacity;
89+
}
90+
91+
int main()
92+
{
93+
int x = 0;
94+
95+
stack st;
96+
97+
x = st.size();
98+
std::cout << "Size=> " << x << std::endl;
99+
100+
st.push(3);
101+
st.push(1);
102+
st.push(12);
103+
st.push(23);
104+
st.push(44);
105+
st.push(53);
106+
st.push(0);
107+
st.push(-1);
108+
st.push(-42);
109+
st.push(0);
110+
st.push(-100);
111+
112+
x = st.peek();
113+
std::cout << "Top=> " << x << std::endl;
114+
115+
st.pop();
116+
st.pop();
117+
118+
if (st.is_empty())
119+
std::cout << "Stack is empty!" << std::endl;
120+
else
121+
std::cout << "Stack is not empty!" << std::endl;
122+
123+
x = st.size();
124+
std::cout << "Size=> " << x << std::endl;
125+
126+
if (st.is_full())
127+
std::cout << "Stack is full!" << std::endl;
128+
else
129+
std::cout << "Stack is not full!" << std::endl;
130+
131+
return 0;
132+
}

0 commit comments

Comments
 (0)