0x00数据结构——C语言实现(队列)
实现
#ifndef QUEUE_H
#define QUEUE_H
typedef enum {
false = 0 ,
true
} BOOL;
struct node;
typedef struct node node;
typedef node *pos;
typedef node *queue ;
queue create_queue(void );
BOOL is_empty(queue Q);
BOOL is_full(queue Q);
BOOL set_empty(queue Q);
BOOL delete_queue(queue *Q);
int dequeue(queue Q);
int front_queue(queue Q);
void enqueue(queue Q, int x);
void print_queue(queue Q);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
#define MAXQUEUE 100
struct node {
int val;
struct node *next;
struct node *pre;
};
queue create_queue(void )
{
queue tmp = (queue )malloc (sizeof (node));
tmp->val = 0 ;
tmp->next = NULL;
tmp->pre = NULL;
return tmp;
}
BOOL is_empty(queue Q)
{
return (Q->val == 0 );
}
BOOL is_full(queue Q)
{
return (Q->val == MAXQUEUE);
}
BOOL set_empty(queue Q)
{
node *tmp = Q->next;
while (tmp!=NULL) {
(tmp->pre)->next = tmp->next;
(tmp->next)->pre = tmp->pre;
free (tmp);
(Q->val)--;
tmp = Q->next;
}
return true ;
}
BOOL delete_queue(queue *Q)
{
set_empty(*Q);
free (*Q);
*Q = NULL;
return true ;
}
int dequeue(queue Q)
{
if (is_empty(Q)) {
printf ("Q is empty\n" );
return -1 ;
}
node *tmp = Q->next;
int r = tmp->val;
Q->next = tmp->next;
if (tmp->next != NULL) {
(tmp->next)->pre = NULL;
}
(Q->val)--;
return r;
}
int front_queue(queue Q)
{
return (Q->next)->val;
}
void enqueue(queue Q, int x)
{
if (is_full(Q)) {
printf ("Q is full\n" );
}
node *tmp = (queue )malloc (sizeof (node));
tmp->val = x;
if (Q->pre != NULL) {
(Q->pre)->next = tmp;
tmp->pre = (Q->pre);
tmp->next = NULL;
Q->pre = tmp;
} else {
tmp->pre = NULL;
tmp->next =NULL;
Q->pre = tmp;
Q->next = tmp;
}
(Q->val)++;
}
void print_queue(queue Q)
{
node *tmp = Q->next;
if (tmp == NULL) {
printf ("->" );
} else {
while (tmp != NULL) {
printf ("->%d" , tmp->val);
tmp = tmp->next;
}
}
printf ("\n" );
}
实验
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
int main()
{
queue Q;
int i;
Q = create_queue();
for (i = 0 ; i<10 ; i++) {
print_queue(Q);
enqueue(Q, i);
}
while (!is_empty(Q)) {
dequeue(Q);
print_queue(Q);
}
return 0 ;
}
实验结果
->
-> 0
-> 0 -> 1
-> 0 -> 1 -> 2
-> 0 -> 1 -> 2 -> 3
-> 0 -> 1 -> 2 -> 3 -> 4
-> 0 -> 1 -> 2 -> 3 -> 4 -> 5
-> 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6
-> 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
-> 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
-> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
-> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
-> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
-> 4 -> 5 -> 6 -> 7 -> 8 -> 9
-> 5 -> 6 -> 7 -> 8 -> 9
-> 6 -> 7 -> 8 -> 9
-> 7 -> 8 -> 9
-> 8 -> 9
-> 9
->
Time elapsed: 000 :00 :031
Press any key to continue