含义:一种先进先出的存储结构,即只允许一端进行插入操作,另外一端进行删除操作
类型:顺序存储结构(循环队列)和链式存储结构(链队列)
循环队列
含义:头尾相接的顺序存储结构的队列,用数组实现。
结构代码
typedef struct Queue{
//int *pBase;
int data[MAXSIZE];
int front;//头指针
int rear;//尾指针
}QUEUE;
1、初始化
void init(QUEUE *pQ){
//动态分配数组的内存大小
//pQ->pBase=(int *)malloc(sizeof(int)*len);
pQ->front=0;
pQ->rear=0;
}
2、返回队列元素的个数,也就是队列的当前长度
int queueLength(QUEUE *pQ) {
return (pQ->rear - pQ->front+MAXSIZE)%MAXSIZE;
}
3、入队操作
bool enQueue(QUEUE *pQ,int val){
//判断是否为满
if((pQ->rear+1)%MAXSIZE ==pQ->front)
return false;
//队尾加元素
pQ->data[pQ->rear]=val;
//rear指针向后移动一位,若到了最后则转到数组的头部
pQ->rear=(pQ->rear+1)%MAXSIZE;
return true;
}
4、出队操作
bool deQueue(QUEUE *pQ,int *val){
//判断是否为空
if(pQ->front==pQ->rear)
return false;
*val=pQ->data[pQ->front];
pQ->front=(pQ->front+1)%MAXSIZE;
return true;
}
5、遍历操作
void show_queue(QUEUE *pQ){
int i=pQ->front;
while(i!=pQ->rear){
printf("%d ",pQ->data[i]);
i=(i+1)%MAXSIZE;
}
printf("\n");
}
测试代码
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 100
int main()
{
int val;
QUEUE pQ;
init(&pQ);
//添加数据
enQueue(&pQ,1);
enQueue(&pQ,2);
enQueue(&pQ,3);
enQueue(&pQ,4);
enQueue(&pQ,5);
enQueue(&pQ,6);
printf("遍历循环列表\n");
show_queue(&pQ);
//删除数据
deQueue(&pQ,&val);
printf("遍历循环列表\n");
show_queue(&pQ);
}
测试结果
代码下载:http://download.csdn.net/detail/a_person_alone/9487908
链队列
含义:一种只允许尾进头出的单链表
结构代码
//结点结构
typedef struct QNode{
int data;
struct QNode *next;
} QNODE,*QUEUEPTR;
//队列的链表结构
typedef struct {
QUEUEPTR front ,rear;
} LINKQUEUE;
1、初始化
void init(LINKQUEUE *Q){
QUEUEPTR pHead=(QUEUEPTR)malloc(sizeof(QNODE));
//当队列为空时 ,front 和rear都指向头结点
pHead->next=NULL;
Q->front=pHead;
Q->rear=Q->front;
}
2、插入
bool EnQueue(LINKQUEUE *Q,int e){
//分配结点内存
QUEUEPTR pQ=(QUEUEPTR) malloc(sizeof(QNODE));
if(!pQ) {
printf("分配内存失败");
exit(-1);
}
//为新节点赋值
pQ->data=e;
pQ->next=NULL;
//将新节点加到队尾节点
Q->rear->next=pQ;
//将rear移到队尾
Q->rear=pQ;
}
3、删除
void DeQueue(LINKQUEUE *Q,int *val){
QUEUEPTR p;
//判断是否为空
if(Q->front==Q->rear){
printf("队列为空!\n");
exit(-1);
}
//将要删除的队头节点暂时给p
p=Q->front->next;
//将要删除的值赋给val
*val=p->data;
//将原队头指向下一个结点
Q->front->next=p->next;
//如果队头是队尾,则删除后指向头结点,即原队列只有一个元素
if(Q->rear==p)
Q->rear=Q->front;
free(p);
}
4、遍历
void show_queue(LINKQUEUE *Q){
QNODE *temp=Q->front->next;
if(Q->front==Q->rear){
printf("队列为空!\n");
exit(-1);
}
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
测试代码
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//函数声明
void init(LINKQUEUE *Q);
bool EnQueue(LINKQUEUE *Q,int e);
void show_queue(LINKQUEUE *Q);
void DeQueue(LINKQUEUE *Q,int *val);
int main()
{
int val;
LINKQUEUE *P;
init(P);
EnQueue(P,1);
EnQueue(P,2);
EnQueue(P,3);
EnQueue(P,4);
EnQueue(P,1);
EnQueue(P,2);
EnQueue(P,3);
EnQueue(P,4);
show_queue(P);
DeQueue(P,&val);
show_queue(P);
}
测试结果