-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStack_Dynamic.cpp
More file actions
61 lines (46 loc) · 1.13 KB
/
Stack_Dynamic.cpp
File metadata and controls
61 lines (46 loc) · 1.13 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
#include <bits/stdc++.h>
using namespace std;
class Stack {
int *stack, max;
public:
Stack() {
this->stack = new int[0];
this->max = 0;
}
void push(int element) {
int *temp = new int[this->max + 1];
memcpy(temp, this->stack, this->max * sizeof(int));
this->stack = new int[this->max + 1];
for(int i = 0; i < this->max; i++) {
this->stack[i] = temp[i];
}
this->stack[this->max] = element;
this->max++;
}
int pop() {
if( this->max == 0 ) throw "Empty";
int element = this->stack[this->max -1];
int *temp = new int[this->max -1];
memcpy(temp, this->stack, (this->max - 1) * sizeof(int));
this->stack = new int[this->max - 1];
for(int i = 0; i < this->max - 1; i++) {
this->stack[i] = temp[i];
}
this->max--;
return element;
}
};
int main() {
Stack stack;
stack.push(5);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
printf("Pop > %d\n", stack.pop());
printf("Pop > %d\n", stack.pop());
printf("Pop > %d\n", stack.pop());
printf("Pop > %d\n", stack.pop());
printf("Pop > %d\n", stack.pop());
return 0;
}