/* 2010-09-09 */
/* Use a linked list to implement a queue */
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Ifdef d
# Define debug (format,...) printf (format, ##__ va_args __)
# Else
# Define debug (format,...) do {} while (0)
# Endif
Typedef struct queue
{
Int X;
Struct queue * next;
} Queue;
Void init_queue (queue ** qhead) // initialize the queue
{
If (null! = * Qhead)
{
Debug ("in init_queue, you cannot creat a queue here! /N ");
Exit (-1 );
}
* Qhead = (queue *) malloc (sizeof (Queue ));
If (null = * qhead)
{
Debug ("in init_queue, malloc error! /N ");
Exit (-1 );
}
Memset (* qhead, 0, sizeof (Queue ));
// * Qhead-> next = NULL; why not use this sentence ??!!
Debug ("init_queue success! /N ");
}
Void in_queue (queue * quehead, queue * node) //
{
If (null = quehead)
{
Debug ("in in_queue, quehead is null/N ");
Exit (-1 );
}
While (quehead-> next! = NULL)
{
Quehead = quehead-> next;
}
Quehead-> next = (queue *) malloc (sizeof (Queue ));
If (null = quehead-> next)
{
Debug ("in in_queue, malloc error! /N ");
Exit (-1 );
}
Quehead = quehead-> next;
Quehead-> X = node-> X;
Quehead-> next = NULL;
Debug ("in_queue success! /N ");
}
/*************************************** ********************
* Function: the node is out of the queue and free of space.
* Return value: returns a value of the queue type.
**************************************** *******************/
Queue out_queue (queue * qhead) //
{
If (null = qhead)
{
Debug ("in out_queue, qhead is null/N ");
Exit (-1 );
}
If (null = qhead-> next)
{
Debug ("in out_queue, the queue is empty! /N ");
Exit (-1 );
}
Queue ret;
Queue * TMP = qhead-> next;
Qhead-> next = TMP-> next;
Ret. x = TMP-> X; // save data first and then free
Free (TMP );
Debug ("out_queue success! /N ");
Return ret;
}
Int main (void)
{
Queue * quehead = NULL;
Queue node;
Init_queue (& quehead );
Int I;
Char num [] = {1, 2, 3, 4, 5 };
Int Len;
Len = sizeof (Num)/sizeof (Num [0]);
For (I = 0; I <Len; I ++)
{
Node. x = num [I];
In_queue (quehead, & node );
}
Queue test;
For (I = 0; I <Len; I ++)
{
Test = out_queue (quehead );
Printf ("% d/N", test. X );
}
Return 0;
}