-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack using Array.cpp
More file actions
99 lines (76 loc) · 1.95 KB
/
Stack using Array.cpp
File metadata and controls
99 lines (76 loc) · 1.95 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
/*
Time complexity: O(1)
Space complexity: O(N)
Where 'N' is the capacity of the stack.
*/
// Stack class.
class Stack {
public:
// Declare array.
vector<int> myStack;
// Stack size.
int stackSize;
// Maximum size.
int n;
// Constructor function.
Stack(int n) {
// Initialize class objects.
this -> myStack.resize(n);
this -> stackSize = -1;
this -> n = n;
}
// Push function.
void push(int num) {
// Check if stack is not full.
if(stackSize != n - 1) {
// Increment stack size and update array.
++stackSize;
myStack[stackSize] = num;
}
}
// Pop function.
int pop() {
// Check if stack is not empty.
if(stackSize != -1) {
// Decrease size and return element.
--stackSize;
return myStack[stackSize + 1];
}
else {
return -1;
}
}
// Top function.
int top() {
// Check if stack is not empty.
if(stackSize != -1) {
// Return element.
return myStack[stackSize];
}
else {
return -1;
}
}
// To check whether stack is empty or not.
int isEmpty() {
// Check if stack is not empty.
if(stackSize != -1) {
// Return element.
return 0;
}
else {
return 1;
}
}
// To check whether stack is full or not.
int isFull() {
// Check if stack is not empty.
if(stackSize != n - 1) {
// Return element.
return 0;
}
else {
return 1;
}
}
};