-5

what's wrong with this simple Linked List ?

// linked_lst1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

class Node
{
    int data;
    Node* next;
    friend class LinkedList;
};

class LinkedList
{
private:
    Node* s;
public:
    LinkedList() : s(NULL)
    {};

    void add(int x)
    {
        Node* s1 = new Node();
        s1 = s;

        if (!s1)
        {
            s->data = x;

            return;
        }

        while (s1->next)
            s1 = s1->next;

        Node* temp = new Node;
        temp->data = x;


        s1->next = temp;
        temp->next = NULL;
    }

    void showList()
    {
        Node* s1 = new Node;
        s1 = s;

        while (s1)
        {
            cout << s1->data << " ";
            s1 = s1->next;
        }
    }
};

Here is main section :

int main()
{

    LinkedList list;

    list.add(3);
    list.showList();

    return 0;
}

I think there is an assign issue in s->data = x;, but I don't know how to solve it...

Notice that this is just an educational simple code and I don't want to use templates etc.

I think, I got what was wrong.

1 Answers1

1

You make a new node and then immediately overwrite s1 to point to whatever s was pointing to -- you lose all access to the newly created node.

L. Scott Johnson
  • 4,213
  • 2
  • 17
  • 28
  • 1
    @Javadmk It's really important for you that you understand what your code does. Correcting it helps you now and will result in you failing again. Look again at this part of your code: `Node* s1 = new Node(); s1 = s;`. What do you think that this part should do? It might be that you will now realize it, sometimes you are blind to your own code since you think about what it is supposed to do. Try the rubber duckie method, that is, explaining to a rubber duckie (or something else) why every line of code is required and what it does. – Aziuth May 21 '17 at 23:58
  • @Javadmk Another thing, you might want to thing about splitting the code that you have there - I see a possible method `Node* tail();` that searches the last node. Makes it easier to debug when you have a lot of small methods. In this case, it would. – Aziuth May 22 '17 at 00:02