summaryrefslogtreecommitdiff
path: root/c/dataStructure/408/graph/queue/queue.c
blob: 673c59508686f1dffc20be0992138b70170269c0 (plain)
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
71
72
73
74
75
76
77
78
#include "queue.h"

void initQueue(Queue q)
{
    q->qhead = NULL;
    q->qtail = NULL;
}

void enQueue(Queue q, int y)
{
    elem * tmp = (elem*)malloc(sizeof(elem));

    if (!tmp)
        retreat("fail to enQueue");
    tmp->y = y;
    tmp->next = NULL;

    if (!q->qtail)
    {
        q->qtail = tmp;
        q->qhead = tmp;
    }
    else
    {
        q->qtail->next = tmp;
        q->qtail = tmp;
    }
}

int deQueue(Queue q)
{
    bool flag = false;
    if (!q->qhead)
        retreat("Empty queue");
    if (q->qhead == q->qtail)
        flag = true;
    elem * tmp = q->qhead;
    int p = tmp->y;
    q->qhead = tmp->next;
    free(tmp);
    if (flag)
        q->qtail = q->qhead;
    return p;
}

bool emptyQueue(Queue q)
{
    if (q->qhead)
        return false;
    return true;
}

void purgeQueue(Queue q)
{
    elem * tmp;
    while (q->qhead)
    {
        tmp = q->qhead;
        q->qhead = tmp->next;
        free(tmp);
    }
}

void printHead(Queue q)
{
    printf("Queue head is %d\n", q->qhead->y);
}

void printQueue(Queue q)
{
    elem * tmp = q->qhead;
    while (tmp)
    {
        printf("%d  ",tmp->y);
        tmp = tmp->next;
    }
    printf("\n");
}