Answer to Question #242123 in C++ for khan

Question #242123

implement a list data structure discussed above including following operations using array adt. get() update() length() back() next() start() end() remove() add()


1
Expert's answer
2021-09-25T10:03:19-0400
#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;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS