데이터 구조 -- 순서 순환 대기 열과 체인 대기 열

14746 단어 데이터 구조
제1 부분: 순서 순환 대기 열의 실현
 1 //       

 2 #define OK 1

 3 #define MAXSIZE_Q 10

 4 //#define OVERFLOW -2

 5 #define ERROR 0

 6 

 7 typedef int Status;

 8 typedef int QElemtype;

 9 

10 typedef struct{

11     QElemtype *base;  //            

12     int front; //    

13     int rear;  //    

14 

15 }SqQueue;

16 

17 //---------------------              -----------------------------

18 Status InitQueue(SqQueue *q)

19 {

20     //       Q

21     q->base=(QElemtype*)malloc(MAXSIZE_Q*sizeof(QElemtype));

22     if(!q->base) exit(-1); //      

23     q->front=q->rear=NULL;

24     return OK;

25 }

26 

27 int queueLength(SqQueue q)

28 {

29     //  Q     ,     

30     return (q.rear-q.front+MAXSIZE_Q)%MAXSIZE_Q;

31 }

32 

33 bool isFull(SqQueue *q)

34 {

35     if(q->front=(q->rear+1)%MAXSIZE_Q)

36         return true;

37     return false;

38 }

39 

40 bool isEmpty(SqQueue *q)

41 {

42     if(q->front==q->rear)

43         return true;

44     return false;

45 }

46 

47 Status EnQueue(SqQueue *q,QElemtype e)

48 {

49     //    e Q       

50     if ((q->rear+1)%MAXSIZE_Q==q->front)

51     {

52         //   ,       ,     

53         return ERROR;

54     }

55     q->base[q->rear]=e;

56     //     

57     q->rear=(q->rear+1)%MAXSIZE_Q;

58     return OK;

59 }

60 

61 Status DeQueue(SqQueue *q,QElemtype *e)

62 {

63     //     ,   Q     , e   ,   ok,    error

64     if(q->rear==q->front) return ERROR;  //   

65     *e=q->base[q->front];  //         

66     q->front=(q->front+1)%MAXSIZE_Q;

67     return OK;

68 

69 }

70 

71 void displayQueue(SqQueue *q)

72 {

73     if (q->front==q->rear)

74     {

75         printf("    
"); 76 } 77 else{ 78 // 79 int front=q->front; 80 int rear=q->rear; 81 while(front!=rear) 82 { 83 printf("%d
",q->base[front]); 84 front++; 85 } 86 } 87 }

테스트 용례
 1 int main()

 2 {

 3     SqQueue q;

 4     InitQueue(&q);

 5     int i;

 6     for(i=0;i<11;i++){

 7         if(EnQueue(&q,i)==ERROR){

 8             printf("      ,      9 
"); 9 } 10 } 11 printf("the length of queue is %d
",queueLength(q)); //the length of queue is 9 12 int e1,e2,e3,e4,e5; 13 DeQueue(&q,&e1); 14 DeQueue(&q,&e2); 15 DeQueue(&q,&e3); 16 DeQueue(&q,&e4); 17 DeQueue(&q,&e5); 18 printf("%d--%d--%d--%d--%d
",e1,e2,e3,e4,e5); 19 printf("the length of queue is %d
",queueLength(q)); 20 printf("
"); 21 displayQueue(&q); 22 int e6; 23 DeQueue(&q,&e6); 24 printf("
"); 25 displayQueue(&q); 26 system("pause"); 27 return 0; 28 }

좋은 웹페이지 즐겨찾기