vendredi 2 octobre 2015

C++ linked list crashed

I am new on data structure. I am trying to write a linked list for a string and display the list to screen. It crash at Node *p = create("I "); with the warning of access violation writing location. Here is my code, I don't know how to fix it. Please help. Thank you very much.

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

struct Node
{
    string data;
    Node *prev, *next;
};

Node* create (string value)
{
    Node *temp = (Node*)malloc(sizeof(Node));
    if (NULL==temp) return NULL;

    temp->data=value;
    temp->next=NULL;
    temp->prev=NULL;
    return temp;
}

void addHead (Node* head, string value)
{
    Node *temp = new Node;
    temp->data=value;
    temp->next=head;
    head->prev=temp;
    head = temp;
    temp->prev = NULL;
}

void addTail (Node* head, string value)
{
    Node* s = new Node;
    Node* temp = new Node;
    s=head;
    while (s->next!=NULL)
        s = s->next;
    s->next = temp;
    temp->prev = s;
}

void display (Node* head)
{
    if (head==NULL) return;
    else
    {
        cout << head->data << " ";
        display (head->next);
    }
}

int main()
{
    Node *p = create("I ");
    addTail(p, "want ");
    addTail(p, "cookies ");

    display(p);

    return 0;
} 

Aucun commentaire:

Enregistrer un commentaire