Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions CPP/data-structures/ResizableArray.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#ifndef RESIZABLEARRAY_H_
#define RESIZABLEARRAY_H_

template <typename T>
class ResizableArray {
private:
int defaultCapacity = 1;

int numElements;
int maxCapacity;
T *data;

void resizeArray() {
maxCapacity = maxCapacity + 1;
T *temp;
temp = new T[maxCapacity];
for (int i = 0; i < numElements; i++) {
temp[i] = data[i];
}
delete[] data;
data = temp;
}

// Shift elements one position to the right
void shift_elements_right(int start) {
for (int i = numElements; i > start; i--) {
data[i] = data[i - 1];
}
}

// Shift elements one position to the left
void shift_elements_left(int stop) {
for (int i = satop; i < numElements; i++) {
data[i] = data[i + 1];
}
}

public:
ResizableArray() {
numElements = 0;
maxCapacity = defaultCapacity;
data = new T[maxCapacity];
}

~ResizableArray() {
delete[] data;
}

// Adds the specified element at the end of the array.
void add_last(T element) {
if (numElements == maxCapacity) {
resizeArray();
}
data[numElements] = element;
numElements++;
}

// Adds the specified element at the beginning of the array.
void add_first(T element) {
if (numElements == maxCapacity) {
resizeArray();
}
numElements++;
shift_elements_right(0);
data[0] = element;
}

// Removes and returns the last element of the array.
T remove_last() {
if (numElements == 0) return T;
T elem = data[numElements];
numElements--;
return elem;
}

// Removes and returns the first element of the array.
T remove_first() {
if (numElements == 0) return T;
T elem = data[0];
shift_elements_left(0);
numElements--;
return elem;
}

// Checks if the array contains any elements.
bool is_empty() {
if (numElements == 0)
return true;
return false;
}

// Returns the number of elements in the array.
int size() {
return numElements;
}

T *get_data() {
return data;
}
};
#endif // RESIZABLEARRAY_H_