how to implement swap, append, printReverse functions in LinkedList Class in C++?

  append, c++, copy-constructor, data-structures, project

So this is an assignment and I can’t change the parameters or return types of these functions. I’m showing an empty copy constructor because I’m pretty sure I need it for the append and swap function but I don’t know. I think I need to initialize the object "other" in it? This is a LinkedList of strings. I found a way to printReverse() that required recursion but I couldn’t use it because I would have to add a Node* to its parameter.

//copy constuctor 
LinkedList::LinkedList(const LinkedList& rhs)
{

}

void LinkedList::printReverse() const {
    //initialize current, previous and next ptr. 
    Node* cur;
    //making current be at he start of list
    cur = head;
    // declaring and assigning previous/next 
    Node* prev;
    Node* next;
    //making previous/next point to nothing atm. 
    prev = nullptr;
    next = nullptr;
    // traverse while LinkedList is not enpty
    while (cur != nullptr) {
        // define next as current pointing to next
        next = cur->next;
        // where reversing begins 
        cur->next = prev;
        // move ptrs a position ahead
        prev = cur;
        cur = next;
    }
    head = prev; //error here

    while (next != head) {
        cout << cur->value << " " << endl;
        cur = prev;
    }
    cout << head->value << endl;
}
// Appends the values of other onto the end of this LinkedList.
// I think other has to be initalitized in LinkedList copy constructor?
void LinkedList::append(const LinkedList& other) {
    if (head == nullptr) {
        insertToFront(other);
    }
    //allocate a new node
    Node* n = new Node;
    n->value = other; 
    // Traverse the linked list until we get to the last node
    Node* t = head;
    // Stop when we get to the last node
    while (t->next != nullptr) 
    {
        t = t->next;
    }

    // Set the next pointer of the last node to the new node
    t->next = n;

    // Set the new node's next pointer to nullptr (in order to signify it's the new end of the list)
    n->next = nullptr;

}
void LinkedList::swap(LinkedList& other) {
    //allocate new node
    Node* p;
    p = new Node;
    // traverse list while its not empty
    while (head != nullptr) {
        // p is pointing to next node
        p = p->next;
        // I wanted to make the an if loop to check if user input matches value in linked list
        // set that value to  and make p point to that value.
        // but this is just wrong...
        if (p->value == other) {
            //suppose to point to other object
            *p = other;

        }
        // if the values match dont do anything
        else if (p->value != other) {
            return;
        }
    }
}

I’ve really forgoton some basic concepts in C++ I definitely need to review any help/feedback is
appreciated.

Source: Windows Questions C++

LEAVE A COMMENT