Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the code for the following new member function for our SinglyLinkedList cl

ID: 3671370 • Letter: W

Question

Write the code for the following new member function for our SinglyLinkedList class. You should write out the definition of the function, but do not need to write out all of the rest of the class. Your code should use the assert macro to enforce any relevant contracts.

sample code below:

#include

template

class SinglyLinkedNode {

private:

ELT _element;

SinglyLinkedNode* _next;

public:

SinglyLinkedNode(ELT element, SinglyLinkedNode* next) {

    _element = element;

    _next = next;

}

ELT element() { return _element; }

void set_element(ELT element) { _element = element; }

SinglyLinkedNode* next() { return _next; }

void set_next(SinglyLinkedNode* next) { _next = next; }

};

template

class SinglyLinkedListIterator;

template

class SinglyLinkedList {

friend SinglyLinkedListIterator;

private:

SinglyLinkedNode* _head;

int _length;

public:

SinglyLinkedList() {

    _head = nullptr;

    _length = 0;

}

~SinglyLinkedList() { clear(); }

int length() { return _length; }

bool is_empty() { return (nullptr == _head); }

ELT front() {

    assert(!is_empty());

    return _head->element();

}

void add_front(ELT element) {

    SinglyLinkedNode *new_head = new SinglyLinkedNode(element, _head);

    _head = new_head;

    _length++;

}

void remove_front() {

    assert(!is_empty());

    SinglyLinkedNode* new_head = _head->next();

    delete _head;

    _head = new_head;

    _length--;

}

void clear() {

    while (!is_empty()) {

      remove_front();

    }

    // double check invariants

    assert(is_empty());

    assert(0 == _length);

    assert(nullptr == _head);

}

};

template

class SinglyLinkedListIterator {

private:

SinglyLinkedNode* _location;

public:

SinglyLinkedListIterator(SinglyLinkedList* list) {

    assert(list != nullptr);

    _location = list->_head;

}

bool past_end() { return (nullptr == _location); }

ELT get() {

    assert(!past_end());

    return _location->element();

}

void advance() {

    assert(!past_end());

    _location = _location->next();

}

}

Explanation / Answer

void add_after_front(ELT x) {

  assert(!is_empty());

if(_head->next() == nullptr) {

    SinglyLinkedNode *next_element = new SinglyLinkedNode(x, _element);

    _element = next_element;

_head->next() = _element;

    _length++;

}

else {

_location = nullptr;

_last_element = _location->element();

SinglyLinkedNode *new_element = new SinglyLinkedNode(x, _element);

    _element = new_element;

_last_element->next() = _element;

    _length++;

}

}