Darksider13
Darksider13

Reputation: 31

C++ Linked List Not Preserving New Nodes

I'm trying to transition from an almost entirely Java background to getting comfortable with C++. I'm practicing by trying to build a basic Linked List.

#include <iostream>
#include <string>

using namespace std;

struct node
{
    string data;
    node *next = NULL;
};

class linkedlist
{
    public:
    node *head;

    public:
    linkedlist()
    {
        head = NULL;
    }

    void addNode(string s)
    {
        node *newNode = new node;
        newNode->data = s;

        if(head == NULL)
            head = newNode;

        else
        {
            node *temp = head->next;

            while(temp != NULL)
                temp = temp->next;

            temp = newNode;
        }
    }

    void printList()
    {
        node *temp = head;

        while(temp != NULL)
        {
            cout << temp->data << '\n';

            temp = temp->next;
        }
    }
};

The issue at hand is that once I add a new node using void addNode(string s), it does not appear when I attempt to print the list (starting from the head) with void printList().

For example:

int main(int argc, const char * argv[])
{
    int n;
    string str;
    linkedlist list;

    cout << "Please enter the number of strings you'd like to enter:\n";
    cin >> n;

    for(int i = 0;i < n;i++)
    {
        string temp;

        cout << "Enter string #" << i + 1 << '\n';
        cin >> temp;

        list.addNode(temp);
    }

    cout << "This is your linked list: ";

    list.printList();

    return 0;
}

Using main() above, my results become:

This is your linked list: (string 1)

I'm pretty certain I'm using pointers improperly here but I don't see why. I've done as much digging as I can on my own for some clarification on how I could be doing this wrong but I'm coming up blank.

Thanks for any clarification you folks can provide.

Upvotes: 1

Views: 293

Answers (1)

user2088639
user2088639

Reputation:

The problem is here:

        node *temp = head->next;

        while(temp != NULL)
            temp = temp->next;

        temp = newNode;

You're traversing the list, then setting temp to the value of the newNode. When temp goes out of scope, the value for newNode isn't stored anyplace.

What you want to do is set the next pointer of the last node to the value of newNode, i.e.

        node *temp = head;
        while(temp->next != NULL)
            temp = temp->next;
        temp->next = newNode;

The code above traverses the list until it finds a node that doesn't have a next node, and sets its next node to the newNode, thus adding it to the list.

Upvotes: 3

Related Questions