| 1 | (* A singly linked list of T, its nodes from an allocator. *) |
| 2 | module List(T); |
| 3 | import Mem; |
| 4 | import SYSTEM; |
| 5 | |
| 6 | type |
| 7 | Node* = record |
| 8 | next*: ^Node; |
| 9 | val*: T; |
| 10 | end; |
| 11 | List* = record |
| 12 | head*: ^Node; |
| 13 | len*: INT; |
| 14 | a: ^Mem.Allocator; |
| 15 | end; |
| 16 | |
| 17 | (* An empty list, its nodes from a. *) |
| 18 | proc init*(var l: List; a: ^Mem.Allocator); |
| 19 | begin |
| 20 | l := {a: a}; |
| 21 | end; |
| 22 | |
| 23 | (* v at the front; false if the allocator has no room. *) |
| 24 | proc push*(var l: List; v: T): BOOL; |
| 25 | var n: ^Node; |
| 26 | begin |
| 27 | NEW(n, l.a); |
| 28 | if n = nil then return false; end; |
| 29 | n^.val := v; |
| 30 | n^.next := l.head; |
| 31 | l.head := n; |
| 32 | INC(l.len); |
| 33 | return true; |
| 34 | end; |
| 35 | |
| 36 | (* The front value, taken off; false if the list is empty. *) |
| 37 | proc pop*(var l: List): (T, BOOL); |
| 38 | var n: ^Node; v: T; |
| 39 | begin |
| 40 | n := l.head; |
| 41 | if n = nil then return v, false; end; |
| 42 | v := n^.val; |
| 43 | l.head := n^.next; |
| 44 | DEC(l.len); |
| 45 | Mem.free(l.a, ^U8(n)); |
| 46 | return v, true; |
| 47 | end; |
| 48 | |
| 49 | (* The list backwards. *) |
| 50 | proc reverse*(var l: List); |
| 51 | var p, q, next: ^Node; |
| 52 | begin |
| 53 | p := l.head; |
| 54 | q := nil; |
| 55 | while p # nil do |
| 56 | next := p^.next; |
| 57 | p^.next := q; |
| 58 | q := p; |
| 59 | p := next; |
| 60 | end; |
| 61 | l.head := q; |
| 62 | end; |
| 63 | |
| 64 | (* Takes every value off, giving the nodes back. *) |
| 65 | proc clear*(var l: List); |
| 66 | var _ok: BOOL; _v: T; |
| 67 | begin |
| 68 | while l.head # nil do _v, _ok := pop(l); end; |
| 69 | end; |
| 70 | |
| 71 | end List. |