john
john

Reputation: 95

Linked List in C++

i create a simple Linked list use class.in my class,i have 3 method are:push_back(),push_front(),and print() to print list.I have some problem with pointer p in push_front(). When debug by vs 2013,value and next of p is "unable to read memory",and i can't understand that,so pls explain for me.

#include <stdio.h>
#include <iostream>
using namespace std;
class Note
{
public :
    int value;
    Note *next;
public :
    Note(int value)
    {
        this->value = value;
        this->next = NULL;
    }
    Note(int value,Note *next)
    {
        this->value = value;
        this->next = next;
    }
};

class LinkList
{
public :
    Note *head;
public :
    LinkList()
    {
        head = NULL;
    }

    void Push_back(int value)
    {
        Note *p = NULL;
        if (head == NULL)
        {
            head = new Note(value, NULL);
        }
        else
        {
            p = head;
            while (p->next != NULL)
                p = p->next;
            p->next = new Note(value, NULL);
        }
    }

    void Push_front(int value)
    {
        Note *p = NULL;

        p->value = 3;
        p->next = this->head;
    }

    void print()
    {
        Note *p = NULL; 
        p = head;
        while (p != NULL)
        {
            cout << p->value<<endl;
            p = p->next;
        }
    }

int main()
{
    LinkList test;
    test.Push_back(6);
    test.Push_back(5);
    test.Push_back(12);
    test.Push_front(13);
    test.print();


}

Upvotes: 3

Views: 193

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300837

You have not allocated any memory for p to point at:

void Push_front(int value)
{
    Note *p = NULL;
          ^^^^^^^^

    // you are missing an allocation of a Note object:
    // p = new Note;

    p->value = 3;
    p->next = this->head;
}

Upvotes: 4

Related Questions