线性队列
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
char *space;
int len;
int front;
int rear;
}queue;
void init(queue* q,int len)
{
q->len = len;
q->space = (char*)malloc(sizeof(queue)*q->len);
q->front = q->rear = 0;
}
int isempty(queue *q)
{
return q->front == q->rear;
}
int isfull(queue *q)
{
return ((q->rear)+1)%q->len == q->front;
}
void enqueue(queue *q,char ch)
{
q->space[q->rear] = ch;
q->rear = (++q->rear) % q->len;
}
char dequeue(queue *q)
{
char tem = q->space[q->front];
q->front = (++q->front) % q->len;
return tem;
}
void reserve(queue *q)
{
q->front = q->rear;
}
void clearqueue(queue *q)
{
free(q->space);
}
int main(int argc, char *argv[])
{
queue q;
init(&q,26);
if(!isfull(&q))
{
for(char a= 'a';a<'z';a++)
{
enqueue(&q,a);
}
}
while(!isempty(&q))
{
printf("%c ",dequeue(&q));
}
return 0;
}
链式队列
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
char data;
struct _node *next;
}Node;
typedef struct _queue
{
Node *front;
Node *rear;
}queue;
void init(queue *q)
{
q->front = (Node *)malloc(sizeof(Node));
q->front->next = NULL;
q->rear = q->front;
}
int isempty(queue *q)
{
return q->front == q->rear;
}
void enqueue(queue *q,char ch)
{
Node *cur = (Node *)malloc(sizeof(Node));
cur->data = ch;
cur->next = NULL;
q->rear->next = cur;
q->rear = cur;
}
char dequeue(queue *q)
{
char tem;
Node *t = q->front->next;
tem = t->data;
if(t == q->rear)
{
q->rear = q->front;
free(q->front->next);
q->front->next = NULL;
}
else{
q->front->next = t->next;
free(t);
}
return tem;
}
void rereserve(queue *q)
{
Node *t = q->front->next;
q->front->next = NULL;
q->rear = q->front;
Node *head = t;
while(t)
{
head = t->next;
free(t);
t = head;
}
}
void clearqueue(queue *q)
{
rereserve(&q);
free(q->front);
}
int main(int argc, char *argv[])
{
queue q;
init(&q);
for(char ch = 'a';ch<='z';ch++)
{
enqueue(&q,ch);
}
while(!isempty(&q))
printf("%c ",dequeue(&q));
return 0;
}