Write a program that defines a list of integers, then write functions to print, push head and delete head function. Test your functions using a main function.


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <stdlib.h>

struct cell {
  int elem;
  struct cell *next;
};

typedef struct cell cell;

typedef cell *list;

void display_list(list l)
{
  cell *p;
  printf("[");
  p = l;
  while ( p != NULL ) {
    printf("%d ", p->elem);
    p = p->next;
  }
  printf("]\n");
}

void push_head(int e, list *pl)
{
  cell *c;
  list l = *pl;
  c = (cell *)malloc(sizeof(cell));
  c->elem = e;
  c->next = l;
  *pl = c;
}

int empty_list(list l) { return l==NULL; }

int delete_head(list *pl)
{
  cell *c = *pl;
  int e;
  if ( empty_list(c) ) {
    printf("Delete: empty list !\n");
    exit(4);
  }
  e = c->elem;
  *pl = c->next;
  free(c);
  return e;
}

void main() {
  int i, n;
  list l;
  printf("Enter n :\n");
  scanf("%d", &n);
  for ( i=n; i>0; i-- ) {
    push_head(i, &l);
  }
  display_list(l);
  while ( ! empty_list(l) ) {
    i = delete_head(&l);
    printf("Deleted element: %d\n", i);
    display_list(l);
  }
}


Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Checking whether a given binary tree is a BST