-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackArray.cpp
More file actions
93 lines (76 loc) · 2.43 KB
/
StackArray.cpp
File metadata and controls
93 lines (76 loc) · 2.43 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
// C++ code
#include <iostream>
class StackArray{
private:
int top; // index of top element
int capacity; // allocated memory space of array
int *stack; // array representing stack
void DoubleCapacity(); // double the capacity of stack
public:
StackArray():top(-1),capacity(1){ // constructor
stack = new int[capacity]; // initial state: top=-1, capacity=1
}
void Push(int x);
void Pop();
bool IsEmpty();
int Top();
int getSize();
};
void StackArray::DoubleCapacity(){
capacity *= 2; // double capacity
int *newStack = new int[capacity]; // create newStack
for (int i = 0 ; i < capacity/2; i++) { // copy element to newStack
newStack[i] = stack[i];
}
delete [] stack; // release the memory of stack
stack = newStack; // redirect stack to newStack
}
void StackArray::Push(int x){
if (top == capacity - 1) { // if stack is full, double the capacity
DoubleCapacity();
}
stack[++top] = x; // update top and put x into stack
}
void StackArray::Pop(){
if (IsEmpty()) { // if stack is empty, there is nothing to pop
std::cout << "Stack is empty.\n";
return;
}
top--; // update top
// stack[top] = 0; // (*1)
// stack[top].~T(); // (*2)
}
bool StackArray::IsEmpty(){
// if (top == -1) {
// return true;
// }
// else {
// return false;
// }
return (top == -1);
}
int StackArray::Top(){
if (IsEmpty()) { // check if stack is empty
std::cout << "Stack is empty.\n";
return -1;
}
return stack[top]; // return the top element
}
int StackArray::getSize(){
return top+1; // return the number of elements in stack
}
int main(){
StackArray s;
s.Pop();
s.Push(14);
s.Push(9);
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
s.Push(7);
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
s.Pop();
s.Pop();
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
s.Pop();
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
return 0;
}