File: queue.c

package info (click to toggle)
neverball 1.6.0%2Bgit20180603-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 152,384 kB
  • sloc: ansic: 27,402; makefile: 454; cpp: 208; xml: 177; sh: 161
file content (70 lines) | stat: -rw-r--r-- 1,348 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
 * Copyright (C) 2009 Neverball authors
 *
 * NEVERBALL is  free software; you can redistribute  it and/or modify
 * it under the  terms of the GNU General  Public License as published
 * by the Free  Software Foundation; either version 2  of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT  ANY  WARRANTY;  without   even  the  implied  warranty  of
 * MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
 * General Public License for more details.
 */

#include <stdlib.h>
#include <assert.h>
#include "queue.h"
#include "list.h"

struct queue
{
    List head;
    List tail;
};

Queue queue_new(void)
{
    Queue new;

    if ((new = malloc(sizeof (*new))))
        new->head = new->tail = list_cons(NULL, NULL);

    return new;
}

void queue_free(Queue q)
{
    assert(queue_empty(q));
    free(q->head);
    free(q);
}

int queue_empty(Queue q)
{
    assert(q);
    return q->head == q->tail;
}

void queue_enq(Queue q, void *data)
{
    assert(q);

    q->tail->data = data;
    q->tail->next = list_cons(NULL, NULL);

    q->tail = q->tail->next;
}

void *queue_deq(Queue q)
{
    void *data = NULL;

    if (!queue_empty(q))
    {
        data    = q->head->data;
        q->head = list_rest(q->head);
    }

    return data;
}