(* A singly linked list of T, its nodes from an allocator. *) module List(T); import Mem; import SYSTEM; type Node* = record next*: ^Node; val*: T; end; List* = record head*: ^Node; len*: INT; a: ^Mem.Allocator; end; (* An empty list, its nodes from a. *) proc init*(var l: List; a: ^Mem.Allocator); begin l := {a: a}; end; (* v at the front; false if the allocator has no room. *) proc push*(var l: List; v: T): BOOL; var n: ^Node; begin NEW(n, l.a); if n = nil then return false; end; n^.val := v; n^.next := l.head; l.head := n; INC(l.len); return true; end; (* The front value, taken off; false if the list is empty. *) proc pop*(var l: List): (T, BOOL); var n: ^Node; v: T; begin n := l.head; if n = nil then return v, false; end; v := n^.val; l.head := n^.next; DEC(l.len); Mem.free(l.a, ^U8(n)); return v, true; end; (* The list backwards. *) proc reverse*(var l: List); var p, q, next: ^Node; begin p := l.head; q := nil; while p # nil do next := p^.next; p^.next := q; q := p; p := next; end; l.head := q; end; (* Takes every value off, giving the nodes back. *) proc clear*(var l: List); var _ok: BOOL; _v: T; begin while l.head # nil do _v, _ok := pop(l); end; end; end List.