循环队列M

 1 #include<stdio.h>

 2 #include<stdlib.h>

 3 #define TRUE 1

 4 #define FALSE 0

 5 #define ERROR 0

 6 #define OK 1

 7 #define OVERFLOW -2

 8 #define MAXQSIZE 100

 9 #define LEN sizeof(QElemType)

10 typedef int Status;

11 typedef int QElemType;

12 typedef struct

13 {

14     QElemType *base;

15     int front;

16     int rear;

17 }SqQueue;

18 Status InitQueue(SqQueue &Q)//创建一个队列.

19 {

20     Q.base=(QElemType *)malloc(LEN);

21     if(!Q.base) exit(FALSE);

22     Q.front=Q.rear=0;

23     return OK;

24 }

25 int QueueLength(SqQueue Q)

26 {

27     return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;

28 }

29 Status EnQueue(SqQueue &Q,QElemType e)//插入函数,用于在队尾插入数据e

30 {

31     if((Q.rear+1)%MAXQSIZE==Q.front) return OVERFLOW;

32     Q.base[Q.rear]=e;

33     Q.rear=(Q.rear+1)%MAXQSIZE;

34     return OK;

35 }

36 Status DeQueue(SqQueue &Q,QElemType &e)//删除函数,删除队头元素,并把值赋予e

37 {

38       if(Q.front==Q.rear) return ERROR;

39        e=Q.base[Q.front];

40        Q.front=(Q.front+1)%MAXQSIZE;

41        return OK;

42 }

43 Status PrintQueue(SqQueue Q)//打印队列

44 {

45     QElemType e;

46     int n=QueueLength(Q);

47     printf("队列元素为:");

48     printf("\n********************\n");

49     while(n--)

50     {

51         DeQueue(Q,e);

52         printf("%d ",e);

53     }

54     printf("\n********************\n");

55     return OK;

56 }

57 Status ClearQueue(SqQueue &Q)//清空队列

58 {

59     Q.front=Q.rear=0;

60     return OK;

61 }        

62 Status main()

63 {

64     SqQueue Q;

65     QElemType e; 

66     InitQueue(Q);

67     int n;

68     puts("请输入队列的长度:");

69     scanf("%d",&n);

70     puts("请输入队列元素:");

71     while(n--)

72     {

73         scanf("%d",&e);

74         EnQueue(Q,e);

75     }

76     PrintQueue(Q);

77     puts("请输入你要插入的元素:");

78     scanf("%d",&e);

79     EnQueue(Q,e);

80     PrintQueue(Q);

81     puts("删除元素:");

82     DeQueue(Q,e);

83     printf("你所删除的元素为:%d\n",e);

84     PrintQueue(Q);

85     ClearQueue(Q);

86     system("pause");

87     return OK;

88 }

你可能感兴趣的:(队列)