Skip to content

Commit 5136687

Browse files
committed
add stack
1 parent 4dbcd7f commit 5136687

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

Stack/stack

13.8 KB
Binary file not shown.

Stack/stack.cpp

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#include <iostream>
2+
3+
class Stack{
4+
int _maxSize;
5+
int _top;
6+
int *_data;
7+
8+
public:
9+
Stack(int capacity)
10+
{
11+
_maxSize = capacity;
12+
_top = -1;
13+
_data = new int(_maxSize);
14+
}
15+
16+
int size()
17+
{
18+
return _top+1;
19+
}
20+
21+
bool isEmpty()
22+
{
23+
return (_top == -1);
24+
}
25+
26+
bool isFull()
27+
{
28+
return (_top == _maxSize-1);
29+
}
30+
31+
void push(int datum)
32+
{
33+
if (isFull())
34+
{
35+
std::cout<<"The Stack is full!"<<std::endl;
36+
return;
37+
}
38+
_data[++_top] = datum;
39+
}
40+
41+
int peek()
42+
{
43+
if (isEmpty())
44+
{
45+
std::cout<<"Stack is empty!"<<std::endl;
46+
return 0;
47+
}
48+
return _data[_top];
49+
}
50+
int pop()
51+
{
52+
if(isEmpty())
53+
{
54+
std::cout<<"Nothing to pop!"<<std::endl;
55+
return 0;
56+
}
57+
return _data[--_top];
58+
}
59+
};
60+
61+
62+
int main()
63+
{
64+
Stack* st = new Stack(5);
65+
66+
st->push(1);
67+
st->push(2);
68+
st->push(3);
69+
70+
std::cout<<"Top element is "<<st->peek()<<std::endl;
71+
std::cout<<"Stack size is "<<st->size()<<std::endl;
72+
73+
st->pop();
74+
st->pop();
75+
st->pop();
76+
77+
if(st->isEmpty())
78+
{
79+
std::cout<<"Stack is empty"<<std::endl;
80+
}
81+
else
82+
{
83+
std::cout<<"Stack is not empty"<<std::endl;
84+
}
85+
86+
return 0;
87+
}

0 commit comments

Comments
 (0)