I'm teaching myself data structures and would really appreciate some feedback on my stack implementation.
A couple of things I'm not sure if I should be doing:
- creation of the array and pointer using
new
- style
// Implement 3 stacks with one array
#include <iostream>
class SingleArrayStacks{
private:
int stack_size;
int *array;
int *pointers;
int get_top_position(int stack_num){
return (stack_num * stack_num) + pointers[stack_num];
}
public:
SingleArrayStacks (int array_size = 100, int num_stacks = 3) {
array = new int[array_size];
pointers = new int[num_stacks];
stack_size = array_size / num_stacks;
std::fill_n(pointers, num_stacks, -1);
}
~SingleArrayStacks (){
delete[] array;
delete[] pointers;
}
void print_stack (int stack_num) const {
std::cout << "Current stack state: ";
for (int i = 0; i < sizeof(array); i++) {
std::cout << array[i];
}
std::cout << std::endl;
}
bool is_empty(int stack_num) const {
return pointer[stack_num] == -1;
}
void push (int stack_num, int val) {
if (pointers[stack_num] > stack_size) {
throw std::runtime_error("Stack is full");
} else {
array[get_top_position(stack_num) + 1] = val;
pointers[stack_num]++;
}
}
int pop(int stack_num){
if (is_empty(stack_num) {
throw std::runtime_error("Stack is empty");
} else {
int val = array[get_top_position(stack_num)];
array[get_top_position(stack_num)] = NULL;
pointers[stack_num]--;
return val;
}
}
int top(int stack_num){
if (is_empty(stack_num) {
throw std::runtime_error("Stack is empty");
} else {
return array[get_top_position(stack_num)];
}
}
};