Linked List in C

946 views Asked by At

I'm having problem with double linked lists: I can't get data from nodes throgh another node. This way: node->prev->prev. But node->prev is fine. Anyone knows why?

The code:

/*Add value - right side*/
void addListRight(doubleList *node, int value)
        {
        doubleList *newNode;
        newNode = createList();
        newNode->val = value;
        newNode->right = node->right;
        newNode->left = node;
        node->right->left = newNode; /*<-Error start here - 'segmentation error' or something like this*/
        node->right = newNode;
        }

Using Google, I found that some guys put () like this: (node->right)->right. I tryed it but the result is the same.

Using GCC/Ubuntu 10.10

*I would like to say the proprer word for '->' but I don't know it in English. My bad.. sorry! Same about the tags of this question!

2

There are 2 answers

3
Eric Giguere On BEST ANSWER

You should check for NULL before using a pointer like that. There will be no prev at the head of the list.

1
AudioBubble On

It looks like you're getting a segmentation fault error. This means you are trying to access invalid memory. My guess is that you haven't allocated node->right or it's NULL. Make sure all your pointers are valid and have been allocated properly.

For reference, here is an example linked list implementation:

#include <stdio.h>
#include <stdlib.h>

typedef struct doubleList doubleList;
struct doubleList
{
   int value;
   doubleList *left, *right;
};

doubleList *addListRight(doubleList *node, int value)
{
    doubleList *newNode;
    newNode = malloc(sizeof(doubleList));
    if(newNode == NULL)
    {
        return NULL;
    }
    newNode->value = value;
    newNode->left = NULL;
    newNode->right = NULL;
    if(node != NULL)
    {
        newNode->left = node;
        node->right = newNode;
    }
    return newNode;
}

int main(int argc, char **argv)
{
    doubleList *list = addListRight(NULL, 5);
    addListRight(list, 2);

    // Outputs: 5, 2
    printf("%d, %d", list->value, list->right->value);

    return 0;
}