Error with Push_back function for a LinkedList?

1.1k views Asked by At

So, I've been working on a linked list pushback, and every time, I get some weird output, can someone help see what I'm doing wrong?

void IntList::push_back(int ne) {
if(head == NULL)
    tail = head = new IntNode(ne);

IntNode *nes = new IntNode(ne);
IntNode *remp = head;
while (remp->next != NULL)
    remp = remp->next;
remp->next = nes;
}

I've been getting some weird outputs, my calls are

IntList a;
a.push_back(46);
a.push_back(20);
a.push_back(777);
a.select_sort();
a.insert_sorted(800);
a.display();
cout << endl;

and it outputs 20 46 46 777 800

1

There are 1 answers

2
eMad On BEST ANSWER

When the list is empty, push only a single item and return

if(head == nullptr) // using nullptr instead of NULL
{
    tail = head = new IntNode(ne);
    head->next = nullptr;
    return;
}

Because in case of 1st time push, the item would be inserted twice.