Issue with implementing linked list

I am trying to implement a simple list of links. The initial value was inserted successfully, but the following items are not entered correctly. Please help me decide what the error is. Thank you in gratitude.

#include<iostream>

using std::cout;

class node
{
    public:
        node():next(0){}
        void setNext(node *next){ next = next; }
        node* getNext(){ return next; }
        void setValue(int val){ value = val; }
        int getValue(){ return value; }

    private:
        int value;
        node *next;
};

class list
{
    public:
        list():head(new node()),len(0){}
        bool insert(int value);
        //bool remove(int value);
        int valueAt(int index);
        int length();

    private:
        node *head;
        int len;

};

bool list::insert(int value)
{
    node *current = 0;
    node *previous = 0;
    node *temp = 0;

    temp = new node();
    temp->setValue(value);

    current = head;
    previous = head;

    while((temp->getValue())>(current->getValue()))
    {
        previous = current;
        current = current->getNext();

        if(!current)
        {
            break;
        }
    }

    if(current == head)
    {
        temp->setNext(current);
        head = temp;

        len++;
    }
    else
    {
        temp->setNext(current);
        previous->setNext(temp);

        len++;
    }
}

int list::valueAt(int index)
{
    if((index < len) && (index >= 0))
    {
        node *current = 0;
        current = head;
        int count = 0;

        while(count < index)
        {
            current = current->getNext();
            count++;
        }

        return (current->getValue());
    }
    else
    {
        return -1;
    }
}


int main()
{
    list myList;

    myList.insert(5);
    myList.insert(20);
    myList.insert(10);

    cout<<"Value at index 1 : "<<myList.valueAt(1);

    return 0;
}
+3
source share
1 answer

After a quick glance, perhaps the problem is:

void setNext(node *next){ next = next; }

You assign a variable to yourself because local variables outshine instance variables. Try changing it to

void setNext(node *next){ this->next = next; }

In other notes:

  • As list::listyou probably do not need to be initialized headbefore new node. This will mean that your linked list will have one arbitrary node at creation, but has a length of 0. You should consider setting headto NULL.

  • node value. .

  • -1 - " " list::valueAt, node .

  • , list slist, , .

+3

All Articles