顺序队列
总代码
#include <iostream>
using namespace std;
#define MaxSize 50
typedef struct{
int data[MaxSize];
int f,r;
}SqQueue;
bool isEmpty(SqQueue Q){
if(Q.r==Q.f)return true;
else return false;
}
void InitQueue(SqQueue &Q){
Q.r=Q.f=0;
}
bool EnQueue(SqQueue &Q,int x){
if((Q.r+1)%MaxSize==Q.f)return false;
Q.data[Q.r]=x;
Q.r=(Q.r+1)%MaxSize;
return true;
}//Èë¶Ó
bool DeQueue(SqQueue &Q){//³ö¶Ó
if(Q.r==Q.f)return false;
Q.f=(Q.f+1)%MaxSize;
return true;
}
int main()
{
Queue()
cout << "Hello world!" << endl;
return 0;
}
队列的定义
#define MaxSize 50
typedef struct{
int data[MaxSize];
int f,r;//头f尾r指针
}SqQueue;
判空
头尾指针初始在同一位置,所以头尾指针相等时队列为空
bool isEmpty(SqQueue Q){
if(Q.r==Q.f)return true;
else return false;
}
初始化
让头尾指针指向同一位置
void InitQueue(SqQueue &Q){
Q.r=Q.f=0;
}
入队
牺牲一个空间位,来作为队满标记,也就是队尾指针比队首指针小1的时候,就判断队满(如果不牺牲一个空间位,用队尾队首指针相同来判断队满,会与判空条件冲突)
元素插入队尾,队尾指针进1
bool EnQueue(SqQueue &Q,int x){
if((Q.r+1)%MaxSize==Q.f)return false;
Q.data[Q.r]=x;
Q.r=(Q.r+1)%MaxSize;
return true;
}
当然,也可以不牺牲空间位,可以使用size标记,每存入一位size+1,每出队一次size-1,用size=0判空,或者size==MaxSize判满
或者同时用 队尾队首指针相等判断空或满:
设置一个flag初值为0,
出队的时候,如果flag0且首位指针相等,则队空,
出队的时候,令flag=0,表示刚刚出队过
入队的时候,如果flag1且首位指针相等,则队满,
入队的时候,令flag=1,表示刚刚入队过
因为只有入队才可能队满,只有出队才可能队空。
出队
如果首尾相等,则队空
出队以后队头指针进1
bool DeQueue(SqQueue &Q){
if(Q.r==Q.f)return false;
Q.f=(Q.f+1)%MaxSize;
return true;
}
链式队列
总代码
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode;
typedef struct LinkQueue{
LinkNode *f,*r;
}LinkQueue;
void InitQueue(LinkQueue &Q){
Q.f=Q.r=(LinkNode*)malloc(sizeof(LinkNode));
Q.f->next=NULL;
}
bool isEmpty(LinkQueue &Q){
if(Q.f==Q.r)return true;
else return false;
}
void EnQueue(LinkQueue &Q,int x){
LinkNode *s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=x;s->next=NULL;//队尾 链尾
Q.r->next=s;
Q.r=s;
}
bool DeQueue(LinkQueue &Q){
if(Q.f==Q.r)return false;
LinkNode *p=Q.f->next;
Q.f->next=p->next;
if(Q.r==p)
Q.r=Q.f;//只有一个结点,删除后要变为空
free(p);
return true;
}
int main()
{
cout << "Hello world!" << endl;
return 0;
}
队列的定义
下面是定义一个队列,有首尾指针
上面是定义一个结点的数据结构
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode;
typedef struct LinkQueue{
LinkNode *f,*r;
}LinkQueue;
初始化
因为首尾指针前面定义的时候已经 LinkNode *f,r定义了类型,所以
Q.f=Q.r=(LinkNode)malloc(sizeof(LinkNode));前面不需要加东西了
注意这是带头结点的链表
void InitQueue(LinkQueue &Q){
Q.f=Q.r=(LinkNode*)malloc(sizeof(LinkNode));
Q.f->next=NULL;
}
判空
逻辑上和顺序队列一样,首位指针一样则队空
bool isEmpty(LinkQueue &Q){
if(Q.f==Q.r)return true;
else return false;
}
入队
不需要判断队满
入队直接单链表尾插法
void EnQueue(LinkQueue &Q,int x){
LinkNode *s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=x;s->next=NULL;//队尾 链尾
Q.r->next=s;
Q.r=s;
}
出队
首尾指针一样则队列为空返回false
剩下的就和带头结点的单链表头插法一样了
需要注意的是,如果只有一个结点时,需要手动把队列的尾指针移到队头,因为一般情况下,出队是从队头移出,队尾指针永远指向末尾,当只剩一个元素要出队时,如果不动队尾指针会无家可归~
bool DeQueue(LinkQueue &Q){
if(Q.f==Q.r)return false;
LinkNode *p=Q.f->next;
Q.f->next=p->next;
if(Q.r==p)
Q.r=Q.f;//只有一个结点,删除后要变为空
free(p);
return true;
}
如有错误,欢迎指正!