Search code examples
cstructlinked-listhead

Linked lists, how to insert if head does not exist?


I got a linked list, which should save the Outcome (W or L) and the gained/lost points for each match. All good so far, but I'm getting trouble when the head does not exist/is empty. I also realized I have a pretty bad overview of how to implement linked lists, anyone got good and understandable resources? Anyway this is my code:

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

struct node {
  int point;
  char outcome;
  struct node *next;
};

void add(struct node *data){
    if(data == NULL){
    data = malloc(sizeof(struct node));
    printf("Outcome and points?\n");
    int point;
    char outcome;
    scanf("%c %d",&outcome,&point);
    fgetc(stdin);
    data->point=point;
    data->outcome=outcome;
    data->next=NULL;
    }else{
        struct node *current= data;
        while(current->next != NULL){
            current = current->next;
        }
        current->next = malloc(sizeof(struct node));
        current=current->next;
        printf("Outcome and points?\n");
        int point;
        char outcome;
        scanf("%c %d",&outcome,&point);
        fgetc(stdin);
        current->point=point;
        current->outcome=outcome;
        current->next=NULL;
    }

}

void print(struct node *data){
    struct node *current = data;
    while(current != NULL){
        printf("%c with %3d\n",current->outcome,current->point);
        current = current->next;
    }
}

int main()
{
    struct node *head=NULL;     
    add(head); 
    add(head);
    add(head); 
    print(head);
}

Any help would be appreciated :)


Solution

  • When you execute:

    void add(struct node *data){
        if(data == NULL){
        data = malloc(sizeof(struct node));
    

    the value of head does not change in the calling function.

    Suggest a change of strategy.

    struct node* add(struct node *head)
    {
       if(head == NULL){
          head = malloc(sizeof(struct node));
          printf("Outcome and points?\n");
          int point;
          char outcome;
          scanf("%c %d",&outcome,&point);
          fgetc(stdin);
          head->point=point;
          head->outcome=outcome;
          head->next=NULL;
       }else{
          struct node *current= head;
          while(current->next != NULL){
             current = current->next;
          }
          current->next = malloc(sizeof(struct node));
          current=current->next;
          printf("Outcome and points?\n");
          int point;
          char outcome;
          scanf("%c %d",&outcome,&point);
          fgetc(stdin);
          current->point=point;
          current->outcome=outcome;
          current->next=NULL;
       }
       return head;
    }
    

    And, then change the usage:

    int main()
    {
        struct node *head = add(NULL);     
        add(head);
        add(head); 
        print(head);
    }