Text: Step-by-step write algorithm (linear queue)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
The linear structure here actually refers to the meaning of continuous memory, but the use of the word "linear" appears to be more professional. The previous blog introduced the phenomenon of the structure of the processing method, then on this basis do we add some attributes to form a new data structure type? The answer is yes, the queue is one of them.
The nature of the queue is simple:
(1) queue with head and tail
(2) The queue is pressed into the data from the rear
(3) The queue POPs data from the head
So how does a queue in contiguous memory be implemented?
a) design the queue data structure
typedef struct _QUEUE_NODE{INT* pdata;int length;int head; int tail;int count;} Queue_node;
b) Request queue memory
queue_node* alloca_queue (int number) {queue_node* pqueuenode;if (0 = = number) return Null;pqueuenode = (queue_node*) malloc (sizeof (Queue_node)); assert (NULL! = Pqueuenode); memset (pqueuenode, 0, sizeof (queue_node));p queuenode-> PData = (int*) malloc (sizeof (int) * number), if (null = = Pqueuenode->pdata) {free (pqueuenode); return NULL;} Pqueuenode->length = Number;return Pqueuenode;}
c) Freeing the queue memory
STATUS delete_queue (const queue_node* pqueuenode) {if (null = = Pqueuenode) return False;assert (null! = pqueuenode-> PData), free (pqueuenode->pdata), Free ((void*) pqueuenode), return TRUE;
d) Press the data into the queue
STATUS Insert_queue (queue_node* pqueuenode, int value) {if (NULL = = Pqueuenode) return false;if (Pqueuenode->length = = Pqueuenode->count) return False;pqueuenode->pdata[pqueuenode->tail] = Value;pqueuenode->tail = ( Pqueuenode->tail + 1)% pqueuenode->length; Pqueuenode->count ++;return TRUE;}
e) Eject the data queue
STATUS Get_queue_data (queue_node* pqueuenode, int* value) {if (NULL = = Pqueuenode | | NULL = = value) return false;if (0 = = Pqueuenode->count) return false;*value = Pqueuenode->pdata[pqueuenode->head ];p queuenode-> Pdata[pqueuenode->head] = 0; Pqueuenode-> Count--;p Queuenode->head = (pqueuenode->head + 1)% Pqueuenode->length;return TRUE;}
f) Count how much data is in the current queue
int get_total_number (const queue_node* pqueuenode) {if (NULL = = Pqueuenode) return 0;return Pqueuenode->count;}
g) See how long the total length is when initializing in the queue
int get_total_number (const queue_node* pqueuenode) {if (NULL = = Pqueuenode) return 0;return pqueuenode->length;}
"Preview: Next blog Introduction to the content of linear stacks"
Step-by-step write algorithm (the linear queue)