Array-Based Queue implementation (c)-column ahljjun-blog channel-CSDN. NET
Array-Based Queue implementation (C Language) classification: algorithms and data structures 371 people reading comments (0) Collection Reporting Language cstructnull Test
/*************************************** **
Interface file QUEUE. h
****************************************/
# Ifndef _ QUEUE_H
# Define _ QUEUE_H
# Ifndef BOOL
# Define BOOL int
# Endif
Typedef int Item;
Struct _ Queue;
Typedef struct _ Queue;
Typedef Queue * hQueue; // handle to Queue
HQueue Queue_Init (int nMax );
Void Queue_Destroy (hQueue q );
Void Queue_Put (hQueue q, Item elem );
Item Queue_Get (hQueue q );
Int Queue_Size (hQueue q );
BOOL Queue_IsEmpty (hQueue q );
BOOL Queue_IsFull (hQueue q );
# Endif
/*******************************
Implement file QUEUE. c
*******************************/
# Include <stdio. h>
# Include <stdlib. h>
# Include "QUEUE. h"
Void Error (char * msg)
{
Printf ("Error: % s", msg );
}
// Queue Implementation of opportunity Array
Struct _ Queue
{
Item * elem;
Int head, tail;
Int N;
};
HQueue Queue_Init (int nMax)
{
HQueue que = malloc (sizeof (* que ));
Que-> elem = malloc (nMax + 1) * sizeof (* que-> elem ));
Que-> head = que-> tail = 0;
Que-> N = nMax + 1;
Return que;
}
Void Queue_Destroy (hQueue que)
{
If (que-> elem)
Free (que-> elem );
Que-> elem = NULL;
Free (que );
Que = NULL;
}
Void Queue_Put (hQueue que, Item elem)
{
If (Queue_IsFull (que ))
{
Error ("The Queue Is Full! /N ");
Exit (-1 );
}
Que-> elem [que-> tail] = elem;
Que-> tail = (que-> tail + 1) % (que-> N );
}
Item Queue_Get (hQueue que)
{
Item elem;
If (Queue_IsEmpty (que ))
{
Error ("The Queue Is Empty! /N ");
Exit (-1 );
}
Elem = que-> elem [que-> head];
Que-> head = (que-> head + 1) % (que-> N );
Return elem;
}
Int Queue_Size (hQueue que)
{
Return (que-> tail-que-> head + que-> N) % (que-> N );
}
BOOL Queue_IsEmpty (hQueue que)
{
Return (que-> head = que-> tail );
}
BOOL Queue_IsFull (hQueue que)
{
Return (que-> head = (que-> tail + 1) % (que-> N ));
}
/******************************
Test File main. c
********************************/
# Include <stdio. h>
# Include <stdlib. h>
# Include "QUEUE. h"
Int main ()
{
HQueue q = Queue_Init (7 );
Int t = 7;
While (t)
Queue_Put (q, t --);
Printf ("Queue: % d/n", Queue_Get (q ));
Printf ("Queue: % d/n", Queue_Get (q ));
Printf ("Queue: % d/n", Queue_Get (q ));
Printf ("Queu Size = % d/n", Queue_Size (q ));
Printf ("************************************* */n ");
T = 30;
Queue_Put (q, t --);
Queue_Put (q, t --);
Printf ("Queu Size = % d/n", Queue_Size (q ));
While (! Queue_IsEmpty (q ))
Printf ("Queue: % d/n", Queue_Get (q ));
Queue_Destroy (q );
Return 0;
}