-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresizing_array_stack.cpp
84 lines (70 loc) · 1.17 KB
/
resizing_array_stack.cpp
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
#include <iostream>
#include <cstdlib>
#include <ctime>
#define ull unsigned long long
using namespace std;
class Stack
{
int *arr;
ull int top, sz, start;
void resizeStack(ull int new_size);
public:
Stack(ull int stack_size)
{
start = time(nullptr);
top = -1;
arr = new int[stack_size];
sz = stack_size;
}
~Stack()
{
delete[] arr;
cout << time(nullptr) - start;
}
void push(int item);
int pop();
void display();
};
void Stack::resizeStack(ull int new_size)
{
int *temp = new int[new_size];
memmove(temp, arr, sz * sizeof(int));
delete[] arr;
arr = temp;
sz = new_size;
}
void Stack::push(int item)
{
if (top == sz - 1)
resizeStack(2 * sz);
arr[++top] = item;
}
int Stack::pop()
{
if (top == -1)
{
cout << "Cannot pop: Stack Empty \n";
exit(1);
}
int popped = arr[top--];
if (top <= sz / 4)
resizeStack(sz / 2);
return popped;
}
void Stack::display()
{
for (int i = top; i >= 0; i--)
cout << arr[i] << endl;
}
int main()
{
Stack S(1);
for (ull int i = 0; i < 1000000000; i++)
S.push(2);
// S.display();
// S.pop();
// S.pop();
// S.pop();
// S.display();
return 0;
}