1. 程式人生 > >隊列的 基本操作

隊列的 基本操作

狀態 def pan -s fine 隊列 思考 typedef 新的

一.原理與方法 循環隊列的 插入與 刪除

二..程序清單

三.思考

1. 如果循環隊列的下標不是從0開始,而是是從1開始,那麽頭指針加l 的操作應如何修改?

2. 在循環隊列中判斷隊空和隊滿的條件能否一樣,為什麽?

3. 用另一種不同與上面算法的方法解決“假上溢”問題。

#include<stdio.h>
# include "stdlib.h"
# include "stdio.h"
# include "time.h"

//函數結果狀態代碼
# define  TURE  1
# define  FALSE 0
# define  OK  1
# define  ERROR 
0 # define OVERFLOW -2 # define maxqsize 100 typedef int status; typedef int qelemtype; typedef struct{ qelemtype *base; int front; int rear; }sqqueue; //----------循環隊列的基本操作的算法描述-------- status initqueue(sqqueue &Q){ //構造一個空隊列Q Q.base=(qelemtype*)malloc(maxqsize*sizeof(qelemtype)); if
(!Q.base) return ERROR; Q.front=Q.rear=0; return OK; } int queuelength(sqqueue Q){ //返回Q的元素個數,即對列的長度 return (Q.rear-Q.front+maxqsize)%maxqsize; } status enqueue(sqqueue &Q,qelemtype e){ //插入元素e為Q的新的隊尾元素 if((Q.rear+1)%maxqsize==Q.front) return ERROR; //隊列滿 Q.base[Q.rear]=e; Q.rear=(Q.rear+1
)%maxqsize; return OK; } status dequeue(sqqueue &Q,qelemtype &e){ //若隊列不空,則刪除Q的隊頭元素,用e返回其值,並返回OK //否則返回ERROR if(Q.front==Q.rear) return ERROR; e=Q.base[Q.front]; Q.front=(Q.front+1)%maxqsize; return OK; } int main() { //測試基本操作 int i,e; sqqueue Q; initqueue(Q); printf("\n"); for(i=1;i<=10;i++) { e=i; enqueue(Q,e); } printf("the Length of queue is :%d\n",queuelength(Q)); for(i=1;i<=10;i++) { dequeue(Q,e); printf(" %d",e); } }

隊列的 基本操作