Question

I am trying to write a function to add insert a node to a linked list. The function arguments are the pointer to the pointer to the node where the element should be inserted and the element. I get the error request for member ‘data’ in something not a structure or union request for member ‘next’ in something not a structure or union

Where next and data are the two fields in the linked list

void INSERT(int element, struct Node** position)
{
    //If inserting at front
    if( *position==NULL){

            *position -> data = element;
            *position -> next = NULL;
            return;
    }

    //the node to be inserted is named temp
    struct Node *temp = (struct Node*)malloc(sizeof(struct Node));


    //create cell
    temp -> data = element;
    temp -> next = *position->next;

    *position-> next = temp;


}

The definition of the struct node is

 struct Node
 {
    int data;//payload
    struct Node* next;
 };

The main function calls INSERT

int main()
{
    struct Node *head =(struct Node*)malloc(sizeof(struct Node));

    head -> data =5;
    head -> next  = NULL;

    INSERT(2,&head);
    INSERT(3,&head);



   PRINTLIST(&head);
    return 0;
 }

PRINTLIST just prints the list. It works fine

Was it helpful?

Solution

Probably like this

void INSERT(int element, struct Node **position){
    struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
    temp -> data = element;
    temp -> next = NULL;
    if( *position==NULL){
        *position = temp;
        return;
    }
    temp->next = (*position)->next;
    (*position)->next = temp;
}
//result : //5 -> 3 -> 2 : is inserted next to the head
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top