题目来源:严蔚敏《数据结构》C语言版本习题册 3.28

    1. #include<stdio.h>
    2. #include<stdlib.h>
    3. #ifndef BASE
    4. #define BASE
    5. #define TRUE 1
    6. #define FALSE 0
    7. #define OK 1
    8. #define ERROR 0
    9. #define INFEASIBLE -1
    10. #define OVERFLOW -2
    11. typedef int Status;
    12. typedef int bool;
    13. #endif
    14. // 实现:队列
    15. // 数据结构:循环链表(带头结点)
    16. // 结构体:只设置一个指针指向队尾元素结点(不设头指针)
    17. typedef int ElemType;
    18. typedef struct NodeType{
    19. ElemType data;
    20. struct NodeType *next;
    21. }QNode, *QPtr;
    22. typedef struct{
    23. QPtr rear;
    24. }Queue;
    25. Status InitQueue(Queue *pQ) {
    26. QNode *newNode;
    27. //头结点
    28. newNode = (QNode *)malloc(sizeof(QNode));
    29. if (!newNode) exit(OVERFLOW);
    30. newNode->next = newNode; //指向自己,循环链表
    31. pQ->rear = newNode; //尾指针指向头结点
    32. return OK;
    33. }
    34. Status EnQueue(Queue *pQ, ElemType e) {
    35. QNode *newNode;
    36. newNode = (QNode *)malloc(sizeof(QNode));
    37. if (!newNode) exit(OVERFLOW);
    38. newNode->data = e;
    39. newNode->next = pQ->rear->next;
    40. pQ->rear->next = newNode;
    41. pQ->rear = newNode;
    42. return OK;
    43. }
    44. Status DeQueue(Queue *pQ,ElemType *e) {
    45. QNode *tmp, *top;
    46. if (pQ->rear->next==pQ->rear) return ERROR; //空
    47. top = pQ->rear->next; //头结点
    48. tmp = top->next; //得到队列的第一个元素
    49. *e = tmp->data; //赋值
    50. //删除队列的第一个元素
    51. top->next = tmp->next;
    52. free(tmp);
    53. //如果队列又为空,则需要改变尾指针的指向
    54. if (top->next==top) pQ->rear=top;
    55. return OK;
    56. }
    57. Status Debug(Queue Q, void (*Visit)(ElemType e)) {
    58. QNode *top,*tmp;
    59. printf("----------------\n");
    60. printf("rear指向:%d\n", Q.rear->data); //debug
    61. top = Q.rear->next;
    62. tmp = top;
    63. do {
    64. Visit(tmp->data);
    65. tmp=tmp->next;
    66. }while(tmp!=top);
    67. printf("\n----------------\n");
    68. return OK;
    69. }
    70. void visit(ElemType e) {
    71. printf("%d\t", e);
    72. }
    73. int main() {
    74. int c;
    75. int tmp;
    76. Queue Q;
    77. InitQueue(&Q);
    78. Debug(Q, &visit);
    79. while (1) {
    80. scanf("%d", &c);
    81. switch(c) {
    82. case 1:scanf("%d",&tmp);EnQueue(&Q, tmp);Debug(Q,&visit);break;
    83. case 2:DeQueue(&Q, &tmp);printf("抛出%d\n", tmp);Debug(Q,&visit);break;
    84. }
    85. }
    86. return 0;
    87. }