-2

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();
}
  • 2
    You should also get some learning material from this millennium / tell your teacher the 80s are gone. – Baum mit Augen Aug 24 '16 at 23:06
  • 1
    You should look into "Resource Acquisition Is Initialization" (RAII) and all the lovely modern flavors of pointers in **modern** C++. Here's a good start: http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c – matthew. Aug 24 '16 at 23:08
  • haha ok! wow thanks...! – Jeremi Proulx Aug 24 '16 at 23:08
  • 2
    The code that you've shown us here doesn't return -1. You need to give us an example that reproduces the problem. – David G Aug 24 '16 at 23:08

1 Answers1

1

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;
Tom
  • 939
  • 5
  • 9