WeCodeAcademy

C Linked Lists

A linked list is made of nodes, each holding a value and a pointer to the next node. It grows without needing a big block of memory.

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

struct Node {
  int value;
  struct Node *next;
};

struct Node *push(struct Node *head, int value) {
  struct Node *n = malloc(sizeof(struct Node));
  n->value = value;
  n->next = head;
  return n;
}

int main(void) {
  struct Node *head = NULL;
  for (int i = 1; i <= 4; i++) head = push(head, i * 10);

  for (struct Node *p = head; p != NULL; p = p->next) {
    printf("%d -> ", p->value);
  }
  printf("NULL\n");

  while (head != NULL) {
    struct Node *next = head->next;
    free(head);
    head = next;
  }
  return 0;
}
Output
40 -> 30 -> 20 -> 10 -> NULL
Quick check

What does the last node of a linked list point to?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.