赞
踩
#include<assert.h> #include<stdio.h> #include<stdlib.h> #define size 10 typedef int ElemType; typedef struct SqCycleQueue { ElemType *space; int head; int tail; int queuesize; }SqQue,*SqQuePtr; static int Full(SqQuePtr sq)//判满 { if((sq->tail +1)%sq->queuesize ==sq->head ) return true; return false; } static int AppendSpace(SqQuePtr sq)//队满,申请空间 { int i,j; if(sq->queuesize ==0) { sq->queuesize =size; } ElemType *s=(ElemType *)malloc(sizeof(ElemType)*sq->queuesize *2); assert(s!=NULL); if(s==NULL) return false; //挪数据 for(i=sq->head ,j=0;i!=sq->tail ;i=i+1,j++) { s[j]=sq->space [i]; } sq->head =0; sq->tail =sq->queuesize -1; sq->queuesize *=2; free(sq->space ); sq->space =s; return true; } int Empty_SqQueue(SqQuePtr sq)//判空 { assert(sq!=NULL); if(sq==NULL) exit(0); if(sq->head ==sq->tail ) return true; return false; } int Init_SqQueue(SqQuePtr sq) { assert(sq!=NULL); if(sq==NULL) exit(0); sq->space =(ElemType *)malloc(size * sizeof(ElemType)); if(sq->space ==NULL) exit(0); sq->head =sq->tail =0; sq->queuesize =size; return true; } int Push_SqQueue(SqQuePtr sq,ElemType val)//入队 { assert(sq!=NULL); if(sq==NULL) exit(0); if(Full(sq)&&!AppendSpace (sq))//队满 { return false; } sq->space[sq->tail]=val; sq->tail =(sq->tail +1)%size;//重设队尾指针 return true; } int Pop_SqQueue(SqQuePtr sq)//出队 { assert(sq!=NULL); if(sq==NULL) exit(0); if(Empty_SqQueue (sq)) { return false; } sq->head =(sq->head +1)%size; return true; } ElemType GetHead_SqQueue(SqQuePtr sq)//得到队头元素 { assert(sq!=NULL); if(sq==NULL) exit(0); if(Empty_SqQueue (sq)) { return false; } return sq->space [sq->head ]; } void Clear_SqQueue(SqQuePtr sq )//清空 { assert(sq!=NULL); if(sq==NULL) { printf("%s:%d :: stack is null, so process will over\n", __FILE__, __LINE__); exit(0); } sq->tail =sq->head =0; } void Destroy_SqQueue(SqQuePtr sq)//销毁 { assert(sq!=NULL); if(sq==NULL) { printf("%s:%d :: stack is null, so process will over\n", __FILE__, __LINE__); exit(0); } free(sq->space ); sq->space =NULL; sq->queuesize =sq->tail =0; } void Show(SqQuePtr sq)//打印队中元素 { assert(sq!=NULL); if(sq==NULL) exit(0); for(int i=sq->head;i<sq->tail ;i++) { printf("%d ",sq->space [i]); } printf("\n"); } int main() { SqQue sq; Init_SqQueue(&sq); for(int i=1;i<9;i++) { Push_SqQueue(&sq,i); } Show (&sq); Pop_SqQueue (&sq); Show (&sq); printf("%d\n",GetHead_SqQueue (&sq)); Clear_SqQueue (&sq); Show (&sq); Destroy_SqQueue(&sq); Show (&sq); return 0; }
运行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。