implement a list data structure discussed above including following operations using array adt. get() update() length() back() next() start() end() remove() add()
#include <malloc.h>
template <typename type>
struct list {
private:
type *array;
size_t capacity = 16;
size_t size = 0;
public:
list();
explicit list(size_t);
type get(size_t);
bool update(size_t, type);
size_t length();
type back();
type *start();
type *end();
bool add(type);
};
template<typename type>
list<type>::list() {
this->array = malloc(sizeof(type) * capacity);
}
template<typename type>
list<type>::list(size_t capacity) {
this->capacity = capacity;
this->array = malloc(sizeof(type) * capacity);
}
template<typename type>
type list<type>::get(size_t i) {
if (i < size) {
return this->array[i];
} else {
return nullptr;
}
}
template<typename type>
bool list<type>::update(size_t i, type value) {
if (i < size) {
this->array[i] = value;
return true;
} else {
return false;
}
}
template<typename type>
size_t list<type>::length() {
return this->size;
}
template<typename type>
type list<type>::back() {
if (0 < size) {
return this->array[size-1];
} else {
return nullptr;
}
}
template<typename type>
type *list<type>::start() {
if (0 < size) {
return &this->array[0];
} else {
return nullptr;
}
}
template<typename type>
type *list<type>::end() {
if (0 < size) {
return &this->array[size-1];
} else {
return nullptr;
}
}
template<typename type>
bool list<type>::add(type value) {
if (size < capacity) {
this->array[size] = value;
size = size + 1;
return true;
} else {
return false;
}
}
Comments
Leave a comment