对于顺序队列来说,如果知道队尾元素的位置和队列元素个数,则队首元素的所在位置显然是可以计算的。也就是说,可以用对列中的元素的个数代替队首指针。编写出这种环形队列的初始化,入队,出队和判空。
思想:计算队首位置front:front=(MaxSize-(count-rear-1))%MaxSize。
代码:
typedef struct{ElemType data[MaxSize];int rear,count;
}Queue;
//初始化
void initQ(Queue &Q){Q.rear=MaxSize-1;Q.count=0
}
//入队
bool enQueue(Queue &Q,ElemType x){if(Q.count==MaxSize) return false;Q.rear=(Q.rear+1)%MaxSize;Q.data[Q.rear]=x;Q.count++;return true;
}
//出队
bool deQueue(Queue &Q,ElemType &x){if(Q.count==0) return false;int front = (MaxSize-(Q.count-Q.rear-1))%MaxSize;X=Q.data[front];Q.count--;return true;
}
//判空
bool QueueEmpty(Queue &Q) {return count==0;
}
对于顺序队列来说,如果知道队首元素的位置和队列元素个数,则队尾元素的所在位置显然是可以计算的。也就是说,可以用对列中的元素的个数代替队尾指针。编写出这种环形队列的初始化,入队,出队和判空。
思想:计算队尾位置rear:rear=(front+count-1)%MaxSize。
代码:
typedef struct{ElemType data[MaxSize];int front,count;
}Queue;
//初始化
void initQ(Queue &Q){Q.rear=0;Q.count=0
}
//入队
bool enQueue(Queue &Q,ElemType x){if(Q.count==MaxSize) return false;int rear=(Q.front+Q.count-1)%MaxSize;Q.data[(rear+1)%MaxSize]=x;Q.count++;return true;
}
//出队
bool deQueue(Queue &Q,ElemType &x){if(Q.count==0) return false;x=Q.data[front];Q.front=(Q.front+1)%MaxSize;Q.count--;return true;
}
//判空
bool QueueEmpty(Queue &Q) {return count==0;
}