数据结构之队列的实现
1、顺序队列的实现
?
typedef char ElemType;typedef struct{ ElemType elem[MaxSize]; int front,rear;}SqQueue;void InitQueue(SqQueue *&q){ q=(SqQueue *)malloc(sizeof(SqQueue)); q->front=q->rear=0;}void ClearQueue(SqQueue *&q){ free(q);}int QueueLength(SqQueue *q){ return (q->rear-q->front+MaxSize)%MaxSize;}int QueueEmpty(SqQueue *q){ return q->front==q->rear; }int enQueue(SqQueue *&q,ElemType e){ if((q->rear+1)%MaxSize==q->front){ return 0; } q->rear=(q->rear+1)%MaxSize; q->elem[q->rear]=e; return 1; }int deQueue(SqQueue *&q,ElemType &e){ if(q->front==q->rear){ return 0; } q->front=(q->front+1)%MaxSize; e=q->elem[q->front]; return 1; }
?
2、链式队列的实现
?
typedef char ElemType;typedef struct qnode{ ElemType data; struct qnode *next;}QNode;typedef struct{ QNode *front; QNode *rear;}LiQueue;void InitQueue(LiQueue *&q){ q=(LiQueue *)malloc(sizeof(LiQueue)); q->front=q->rear=NULL; }void ClearQueue(LiQueue *&q){ QNode *p=q->front; if(p!=NULL){ QNode *r=p->next; while(r!=NULL){ free(p); p=r; r=r->next; } free(p); } free(q);}int QueueLength(LiQueue *q){ QNode *p=q->front; int i=0; while(p!=NULL){ i++; p=p->next; } return i; }int QueueEmpty(LiQueue *q){ return q->rear==NULL;}void enQueue(LiQueue *&q,ElemType e){ QNode *qnode; qnode=(QNode*)malloc(sizeof(QNode)); qnode->data=e; qnode->next=NULL; if(q->rear==NULL){ q->front=q->rear=qnode; }else{ q->rear->next=qnode; q->rear=qnode; } }int deQueue(LiQueue *&q,ElemType &e){ QNode *t; if(q->rear==NULL){ return 0; } if(q->front==q->rear){ t=q->front; q->front=q->rear=NULL; }else{ t=q->front; q->front=q->front->next; } e=t->data; free(t); return 1; }?