(********************************************************************)
(*  OCaml code from the book ``Learn Programming with OCaml''       *)
(*  See https://usr.lmf.cnrs.fr/lpo/                                *)
(*                                                                  *)
(*  Sylvain Conchon and Jean-Christophe Filliâtre                   *)
(*  Copyright 2025 Université Paris-Saclay and CNRS                 *)
(*                                                                  *)
(*  Openly licensed via CC BY SA 4.0                                *)
(*  See https://creativecommons.org/licenses/by-sa/4.0/deed.en      *)
(********************************************************************)

(* Program 58 on page 271
   Imperative queues using linked lists *)

type 'a cell = { elt : 'a; mutable next : 'a cell }

type 'a t = 'a cell option ref

let create () =
  ref None

let is_empty q =
  !q = None

let push x q = match !q with
  | None ->
      let rec c = { elt = x; next = c } in
      q := Some c
  | Some last ->
      let c = { elt = x; next = last.next } in
      last.next <- c;
      q := Some c

let pop q = match !q with
  | None ->
      invalid_arg "pop"
  | Some last when last.next == last ->
      q := None;
      last.elt
  | Some last ->
      let first = last.next in
      last.next <- first.next;
      first.elt

This document was generated using caml2html