学习队列

队列

   队列是一种特殊的线性表,主要特点:先进先出,工作中很多时候都需要用队列,要知其然,更知其所以然.用数组实现的顺序队列.

头文件 queue.h

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>


#define N 100                                   //队列的长度

typedef struct queue				//队列的数据结构
{
	int data[N];
	int head;
	int tail;
}Queue;


void initQueue(Queue *p);			//初始化队列

int isEmpty(Queue *p);				//判断队列是否为空

int isFull(Queue *p);				//判断队列是否已满

void showQueue(Queue *p);			//显示队列中所有内容

void enQueue(Queue *p,int key);		        //添加到队列中

int deQueue(Queue *p);				//移出队列

源文件 queue.c 先引入queue.h头文件

判断队列是否为空

int isEmpty(Queue *p)    
{
	if (p->head == p->tail)   //当头部和尾部相等就说明是队列是为空
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

判断队列是否已满

int isFull(Queue *p)     
{
	if (p->tail == N - 1)     //当尾部等数组减一就说明队列满了
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

添加到队列中

void enQueue(Queue *p, int key)				
{
	if (isFull(p) == 1)                           //队列为满的时候,直接返回
	{
		return;
	}
	if (isEmpty(p) == 1)			       //为空的时候,直接放key放到队列中,将尾部下移
	{
		p->data[p->tail] = key;
		p->tail++;
	}
	else
	{
		for (int i = p->tail; i > 0; i--)     //在数据进入队列之前,将队列中所有数据后移
		{
			p->data[i] = p->data[i - 1];    
		}
		p->data[0] = key;		      //将新数据放入头部
		p->tail++;                            //将尾部自增
	}
}

移出队列

int deQueue(Queue *p)    
{
	if (isEmpty(p)==1)                            //为空时,不处理
	{
		return;
	}
	int temp = p->data[p->tail];           
	p->tail--;
	return temp;
}

显示队列中所有数据

void showQueue(Queue *p)    
{
	printf("队列中数据:");
	for (int i = 0; i < p->tail; i++)
	{
		printf("%4d", p->data[i]);
	}
	printf("\n");
}

测试

#include "queue.h"

int main(int argc, char *argv[])
{
	struct queue myQueue;
	initQueue(&myQueue);
	for (int i = 1; i < 10; i++)
	{
		enQueue(&myQueue, i);
		showQueue(&myQueue);
	}
	printf("\n\n\n");
	while (!isEmpty(&myQueue))
	{
		showQueue(&myQueue);
		deQueue(&myQueue);
	}

	system("pause");
	return 0;
}

看一下数据

秋风 2016-07-02