队列的顺序存储结构(c语言实现)

#include 

#define T 1
#define F 0
#define MAXSIZE 20

typedef int Status;
typedef int ElemType;

typedef struct
{
	ElemType data[MAXSIZE];
	int front;
	int rear;
}SqQueue;

Status initQueue(SqQueue* Q);
Status enterQueue(SqQueue* Q, ElemType e);
Status deleteQueue(SqQueue* Q, ElemType* e);
int getLength(SqQueue Q);

int main()
{
	int i = 0, num = 0;
	SqQueue Q;
	initQueue(&Q);
	for (; i < 10; i++)
	{
		enterQueue(&Q, i);
	}
	printf("%d\n", getLength(Q));
	for (; i > 0; i--)
	{
		deleteQueue(&Q, &num);
		printf("%d\n", num);
	}
	printf("%d\n", getLength(Q));

	return 0;
}

Status initQueue(SqQueue* Q)
{
	Q->front = 0;
	Q->rear = 0;
	return T;
}

Status enterQueue(SqQueue* Q, ElemType e)
{
	if ((Q->rear + 1)%MAXSIZE == Q->front)//队列满的判断
	{
		return F;
	}
	Q->data[Q->rear] = e;
	Q->rear = (Q->rear + 1)%MAXSIZE;//将rear指针向后移一位置,若到最后则转到数组头部
	return T;
}

Status deleteQueue(SqQueue* Q, ElemType* e)
{
	if ((Q->rear == Q->front))//队列为空的判断
	{
		return F;
	}
	*e = Q->data[Q->front];
	Q->front = (Q->front + 1)%MAXSIZE;
	return T;
}

int getLength(SqQueue Q)
{
	int len = 0;
	len = (Q.rear - Q.front + MAXSIZE)%MAXSIZE;
	return len;
}

运行结果:

队列的顺序存储结构(c语言实现)_第1张图片

方法二:

#include 

#define T 1
#define F 0
#define MAX 10

typedef struct 
{
	int a[MAX];
	int *in;
	int *out;
	int count;
}queue;

int init(queue *q);
int inQueue(queue *q, int e);
int outQueue(queue *q, int *e);

int main()
{
	int i, e;
	queue q;
	init(&q);
	for (i = 0; i < 10; i++)
	{
		inQueue(&q, i);
	}
	while (q.count != 0)
	{
		outQueue(&q, &e);
		printf("%d\n", e);
	}
	return 0;
}

int init(queue *q)
{
	q->in = q->a;
	q->out = q->a;
	q->count = 0;
	return T;
}

int inQueue(queue *q, int e)
{
	if (MAX == q->count)
	{
		return F;
	}
	*(q->in) = e;
	q->in ++;
	if (q->in == &(q->a[MAX]))
	{
		q->in = q->a;
	}
	q->count ++;
	return T;
}

int outQueue(queue *q, int *e)
{
	if (0 == q->count)
	{
		return F;
	}
	*e = *(q->out);
	q->out ++;
	if (q->out == &(q->a[MAX]))
	{
		q->out = q->a;
	}
	q->count --;
	return T;
}

运行结果:

队列的顺序存储结构(c语言实现)_第2张图片

你可能感兴趣的:(数据结构)