This repository was archived by the owner on Apr 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_resize.cpp
108 lines (104 loc) · 2 KB
/
stack_resize.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
using namespace std;
template <typename T>
class Stack
{
T *ArrayStack;
int Capasity;
int Size;
public:
Stack();
void push(T );
bool pop(T &);
bool top(T &);
bool is_empty();
void print();
int size();
void resize(int );
~Stack();
};
int main()
{
char a;
Stack<char > exapmle;
exapmle.push('d');
exapmle.push('b');
exapmle.push('q');
exapmle.push('k');
exapmle.print();
exapmle.pop(a);
cout << a << endl;
cout << exapmle.size() << endl;
return 0;
}
template <typename T>
Stack<T>::Stack()
{
Capasity = 5;
ArrayStack = new T[Capasity];
Size = 0;
}
template <typename T>
Stack<T>::~Stack()
{
delete [] ArrayStack;
}
template <typename T>
void Stack<T>::print()
{
cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
for (int i = 0; i < Size; i++)
cout << ArrayStack[i] << " ";
cout << endl;
cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
}
template <typename T>
void Stack<T>::push(T value)
{
if (Size == Capasity)
resize(Capasity * 2);
ArrayStack[Size] = value;
Size++;
}
template <typename T>
void Stack<T>::resize(int newSize)
{
// int newSize = (int)(Size * 1.5);
T *NewStack = new T[newSize];
for (int i = 0; i < Size; i++)
NewStack[i] = ArrayStack[i];
delete ArrayStack;
Capasity = newSize;
ArrayStack = NewStack;
}
template <typename T>
bool Stack<T>::pop(T &out)
{
if (is_empty())
return false;
if (Size <= Capasity/4)
resize(Capasity/2);
Size--;
out = ArrayStack[Size];
return true;
}
template <typename T>
bool Stack<T>::top(T &out)
{
if (is_empty())
return false;
out = ArrayStack[Size - 1];
return true;
}
template <typename T>
bool Stack<T>::is_empty()
{
if (Size == 0)
return true;
return false;
}
template <typename T>
int Stack<T>::size()
{
return Size;
}