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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct node
{
int data;
struct node *next;
}
node_t;
typedef struct
{
node_t *head;
node_t *tail;
int count;
}
queue_t;
void queueInit (queue_t * myroot)
{
myroot->head = NULL;
myroot->tail = NULL;
myroot->count = 0;
}
node_t *node_create (int data)
{
node_t *this = malloc (sizeof *this);
if (this != NULL)
{
{
static node_t const z = { 0, NULL };
*this = z;
}
this->data = data;
}
return this;
}
void queuePut (queue_t * myroot, node_t * const mynode)
{
mynode->next = NULL;
if (myroot->tail != NULL)
{
assert (myroot->tail != mynode);
myroot->tail->next = mynode;
}
myroot->tail = mynode;
if (myroot->head == NULL)
myroot->head = mynode;
myroot->count++;
}
node_t *queueGet (queue_t * const myroot)
{
node_t *node;
node = myroot->head;
if (myroot->head == myroot->tail)
{
myroot->tail = NULL;
}
if (myroot->head != NULL)
{
myroot->head = myroot->head->next;
}
myroot->count--;
return node;
}
void queueDestroy (queue_t * myroot)
{
while (myroot->head != NULL)
{
node_t *node = myroot->head;
myroot->head = myroot->head->next;
free (node);
}
}
void queue_print (queue_t * myroot)
{
node_t *p = myroot->head;;
while (p != NULL)
{
printf ("%d -> ", p->data);
p = p->next;
}
printf ("NIL\n");
}
int main (void)
{
queue_t queue;
queueInit (&queue);
{
node_t *const mynode = node_create (12);
queuePut (&queue, mynode);
}
queue_print (&queue);
{
node_t *const mynode = node_create (34);
queuePut (&queue, mynode);
}
queue_print (&queue);
{
node_t *const mynode = node_create (56);
queuePut (&queue, mynode);
}
queue_print (&queue);
{
node_t *mynode = queueGet (&queue);
printf ("data = %d\n", mynode->data);
free (mynode);
}
queue_print (&queue);
{
node_t *mynode = queueGet (&queue);
printf ("data = %d\n", mynode->data);
free (mynode);
}
queue_print (&queue);
queueDestroy (&queue);
queue_print (&queue);
return 0;
} |
Partager