这个是循环队列的实现,至于串及数组这两章,等有空再看,下面将学习树。
源码如下:
#include <stdio.h> #include <stdlib.h> #define MAXQSIZE 8 typedef int QElemType ; typedef struct { QElemType *base; int front; int rear; }SqQueue; int InitSqQueue(SqQueue *S) { S->base = (QElemType *)malloc(sizeof(QElemType)*MAXQSIZE); printf("Init %p ",S->base); if(!S->base) { exit(0); } S->front = S->rear = 0; return 1; } int InsertQueue(SqQueue *S, QElemType e) { if((S->rear + 1)%MAXQSIZE == S->front) { printf("full e: %d !!! ",e); int temp = 0; DeleteQueue(S,&temp); InsertQueue(S,e); return -1; } *(S->base + S->rear) = e; printf("insert %p : %d ",(S->base + S->rear),e); S->rear = (S->rear + 1)%MAXQSIZE; return 1; } int DeleteQueue(SqQueue *S, QElemType * e) { if(S->front == S->rear) { return -1; } *e = *(S->base + S->front); printf("del %p : %d ",(S->base + S->front),*e); S->front = (S->front + 1)%MAXQSIZE; return 1; } void PrintQueue(SqQueue *S) { int *a = S->base; int front = S->front; int rear = S->rear; while(front != rear) { printf("%d ",a[front]); front ++; } printf(" "); } void DestoryQueue(SqQueue *S) { free(S->base); } int main(int argc ,char** argv) { SqQueue S; printf("main %p ",S.base); InitSqQueue(&S); int i = 0; for(i = 0 ; i < 20 ; i++) { InsertQueue(&S,i); } // PrintQueue(&S); DeleteQueue(&S,&i); // PrintQueue(&S); printf("main %p ",S.base); free(S.base); printf("main %p ",S.base); //S.base = NULL; // DestoryQueue(&S); return 1; }
运行结果如下:
root@ubuntu:/mnt/hgfs/E/Lessons/MyExercise/DS/3# ./SqQueue main 0xe344d5 Init 0x822d008 insert 0x822d008 : 0 insert 0x822d00c : 1 insert 0x822d010 : 2 insert 0x822d014 : 3 insert 0x822d018 : 4 insert 0x822d01c : 5 insert 0x822d020 : 6 full e: 7 !!! del 0x822d008 : 0 insert 0x822d024 : 7 full e: 8 !!! del 0x822d00c : 1 insert 0x822d008 : 8 full e: 9 !!! del 0x822d010 : 2 insert 0x822d00c : 9 full e: 10 !!! del 0x822d014 : 3 insert 0x822d010 : 10 full e: 11 !!! del 0x822d018 : 4 insert 0x822d014 : 11 full e: 12 !!! del 0x822d01c : 5 insert 0x822d018 : 12 full e: 13 !!! del 0x822d020 : 6 insert 0x822d01c : 13 full e: 14 !!! del 0x822d024 : 7 insert 0x822d020 : 14 full e: 15 !!! del 0x822d008 : 8 insert 0x822d024 : 15 full e: 16 !!! del 0x822d00c : 9 insert 0x822d008 : 16 full e: 17 !!! del 0x822d010 : 10 insert 0x822d00c : 17 full e: 18 !!! del 0x822d014 : 11 insert 0x822d010 : 18 full e: 19 !!! del 0x822d018 : 12 insert 0x822d014 : 19 del 0x822d01c : 13 main 0x822d008 main 0x822d008 root@ubuntu:/mnt/hgfs/E/Lessons/MyExercise/DS/3#