Jeremi Proulx Jeremi Proulx - 3 months ago 32
C++ Question

Linked list not working in c++

So i'm trying to get the linked list and this is my code so far. Everything look fine when i'm adding a node at the front of my list, but when i try to add my first node at the back, my code compile but return me -1. I'm not sure what's wrong with it but I know it's in the insertBack() function. And by the way, if there's anything else wrong let me know, it's my first try on linked list!
Thanks!

#include "LinkedList.h"
#include <iostream>
#include <stddef.h>

LinkedList::LinkedList()
{
head=NULL;
length=0;
}

void LinkedList::InsertFront(int item)
{
Node *temp = new Node;
temp->data = item;
temp->next = head;
head = temp;
length++;
}

void LinkedList::InsertBack(int item)
{
Node *temp1 = new Node;
temp1 = head;

while(temp1->next != NULL)
{
temp1 = temp1->next;
}
Node *temp = new Node;
temp->data = item;
temp->next = NULL;
temp1->next = temp;

length++;
}

void LinkedList::MakeEmpty()
{
Node *temp;
while(head!= NULL)
{
temp = head;
head = head->next;
delete temp;
}
length;
}

void LinkedList::ShowItems()
{
Node *temp = head;
while(temp != NULL)
{
std::cout<<temp->data<<std::endl;
temp = temp->next;
}
}


LinkedList::~LinkedList()
{
MakeEmpty();
}

Tom Tom
Answer

Make sure head has been allocated before you reference it. This is the most likely source of your problem when you run InsertBack, which depends on having head be initialized already, because it goes through all the elements in the list starting with the first one but assumes the first one has already been allocated.

It also makes an unnecessary memory allocation--it creates a new Node, and then immediately writes over the thing that's pointing to it, so what was the point?

 Node *temp1 = new Node;
 temp1 = head;
Comments