C - Linked lists - Simple example

Below, certainly the most easy example of the linked lists.

Let's see this example as a FILO, meaning First In Last Out:

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

/*                                                                             
** STRUCTURE                                                                   
*/
typedef struct s_list
{
  int   nb;
  struct s_list *next;
} t_list;

/*                                                                             
** ADD                                                                         
*/
t_list  *add(t_list *element, int i)
{
  t_list        *link;

  link = malloc(sizeof(*link));
  link->nb = i;
  link->next = element;
  return (link);
}

/*                                                                             
** DISPLAY                                                                     
*/
void    display(t_list *toDisplay)
{
  while (toDisplay != NULL)
    {
      printf("toDisplay->nb = %d\n", toDisplay->nb);
      toDisplay = toDisplay->next;
    }
}

/*                                                                             
** MAIN                                                                        
*/
int     main()
{
  t_list        *new;
  int   i;

  new = NULL;
  i = 0;
  while (i < 18)
    new = add(new, i++);
  display(new);
  return (0);
}

Result:

toDisplay->nb = 17
toDisplay->nb = 16
toDisplay->nb = 15
toDisplay->nb = 14
toDisplay->nb = 13
toDisplay->nb = 12
toDisplay->nb = 11
toDisplay->nb = 10
toDisplay->nb = 9
toDisplay->nb = 8
toDisplay->nb = 7
toDisplay->nb = 6
toDisplay->nb = 5
toDisplay->nb = 4
toDisplay->nb = 3
toDisplay->nb = 2
toDisplay->nb = 1
toDisplay->nb = 0

Indeed, the first structure to be displayed is the last added. And the last displayed is the first added.

Let's see now the same example but without any return value:

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

typedef struct s_ll
{
  int   nb;
  struct s_ll *next;
} t_ll;

void    add(t_ll **linkedList, int i)
{
  t_ll  *new;

  new = malloc(sizeof(*new));
  new->nb = i;
  new->next = *linkedList;
  *linkedList = new;

}

void    display(t_ll *linkedList)
{
  while (linkedList != NULL)
    {
      printf("linkedList->nb = %d\n", linkedList->nb);
      linkedList = linkedList->next;
    }
}

void    init()
{
  t_ll  *linkedList;
  int   i;
  int   av;

  av = 18;
  i = 0;
  linkedList = NULL;
  while (i < av)
    add(&linkedList, i++);
  display(linkedList);
}

int     main()
{
  init();
  return (0);
}

This time we let a link from the first structure. We use for that the double pointer in our add() function.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.