1.什么是队列?队列是一种受限的线性表,具有先进先出的特点。进行删除的一头为队头(front),进行插入的一头为队尾(rear)。
2.队列分为顺序队列与链式队列。
3.队列的基本操作:入队,出队,存取,判断是否满队和空队。
4.顺序队列经典模型之循环队列。运用取余的方法即可将数组变成循环数组。
#include <stdio.h>
void QInsert(int* a,int data);
void QDelete(int* a);
int front=0;
int rear=0;
int main(){
int a[100];
for(int i=0;i<10;i++){
QInsert(a,i);
}
QDelete(a);
for(int i=front;i<rear;i++){
printf("%d ",a[i]);
}
}
void QInsert(int *a,int data){
a[rear]=data;
rear++;
rear=rear%100;//取余的目的是形成循环队列,节省空间。
}
void QDelete(int *a){
front++;
front=front%100;
}
思考题:原本有三个参数,front,rear,count。count是否必须。
个人观点:我认为不必须,当front与rear相等时,也可确定队列已满。
链式队列:
#include <stdio.h>
#include <malloc.h>
struct Cell{
int data;
Cell* next;
};
void QInsert(int data);
void QDelete();
void print();
Cell* rear=NULL,*front=NULL;
//rear=NULL;
//front=NULL;
int main(){
for(int i=0;i<5;i++){
QInsert(i);
}
QDelete();
print();
}
void QInsert(int data){//在rear队尾插入
Cell* p;
p=(Cell*)malloc(sizeof(struct Cell));
p->data=data;
if(front==NULL){//空队列情况
front=p;
p->next=NULL;
rear=p;
}
p->next=NULL;
rear->next=p;
rear=p;
}
void QDelete(){
Cell* tmp;
if(front==NULL){
printf("Error");
}
tmp=front;
front=front->next;
free(tmp);
if(front==NULL){
rear=NULL;
}
}
void print(){
while(front!=NULL){
printf("%d ",front->data);
front=front->next;
}
}
问题:此处我将front与rear都作为全局变量使用,如果front与rear在main函数中,将如何考虑队列为空的情况???