现在的位置: 首页 > 综合 > 正文

数据结构队列的各种操作

2017年12月19日 ⁄ 综合 ⁄ 共 1614字 ⁄ 字号 评论关闭

 

  1. #include"stdio.h"  
  2. #include"stdlib.h"  
  3. typedef int ElementType;  
  4. typedef struct Queue  
  5. {  
  6.     int rear,front;  
  7.     ElementType *elements;  
  8.     int MaxSize;  
  9. }Queue;  
  10. void InitQueue(Queue *Q,int sz)//初始化  
  11. {  
  12.     Q->MaxSize=sz;  
  13.     Q->elements=(ElementType *)malloc(sizeof(ElementType)*Q->MaxSize);  
  14.     Q->front=Q->rear=0;  
  15. }  
  16. void freeQueue(Queue *Q,int sz)//释放空间  
  17. {  
  18.     free(Q->elements);  
  19. }  
  20. void MakeEmpty(Queue *Q)//置空  
  21. {  
  22.     Q->front=Q->rear=0;  
  23. }  
  24. int Length(Queue *Q)//返回长度  
  25. {  
  26.     return (Q->rear-Q->front+Q->MaxSize)%(Q->MaxSize);  
  27. }  
  28. int IsFull(Queue *Q)//判断是否为满  
  29. {  
  30.     if (Q->rear!=0&&(Q->front==(Q->rear)%(Q->MaxSize)))  
  31.         return 1;  
  32.     else 
  33.         return 0;  
  34. }  
  35. int IsEmpty(Queue *Q)//判断是否为空  
  36. {  
  37.     if(Q->front==Q->rear)  
  38.         return 1;  
  39.     else 
  40.         return 0;  
  41. }  
  42. void EnQueue(Queue *Q)//进队  
  43. {   ElementType item;  
  44.     scanf("%d",&item);  
  45.     while((!IsFull(Q))&&(item!=-1))  
  46.     {  
  47.         Q->elements[Q->rear]=item;  
  48.         Q->rear=(Q->rear+1)%(Q->MaxSize);  
  49.         scanf("%d",&item);  
  50.     }  
  51. }  
  52. ElementType DeQueue(Queue *Q)  
  53. {  
  54.     ElementType item;  
  55.     if(!IsEmpty(Q))  
  56.     {  
  57.         item=Q->elements[Q->front];  
  58.         Q->front=(Q->front+1)%(Q->MaxSize);  
  59.         return item;  
  60.     }  
  61.     else 
  62.     {  
  63.         printf("对空!\n");  
  64.         exit(1);  
  65.     }  
  66. }  
  67. ElementType GetFront(Queue *Q)  
  68. {  
  69.     if(!IsEmpty(Q))  
  70.         return Q->elements[Q->front];  
  71.     else 
  72.     {  
  73.         printf("队空!\n");  
  74.         exit(1);  
  75.     }  
  76. }  
  77. void main()  
  78. {  
  79.     int i;  
  80.     Queue Q;  
  81.     InitQueue(&Q,10);  
  82.     EnQueue(&Q);  
  83.     for(i=0;i<10;i++)  
  84.     if(!IsEmpty(&Q))  
  85.     printf("%-5d",DeQueue(&Q));  

 

本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/817865

【上篇】
【下篇】

抱歉!评论已关闭.