数据结构——循环队列操作

  1 /*
2 循环队列的基本操作,初始化,入队,遍历,出队等操作
3 */
4 #include <stdio.h>
5 #include <malloc.h>
6
7 #define true 1
8 #define false 0
9
10 typedef struct Queue
11 {
12 int *pBase; //定义数组pBase
13 int front;
14 int rear;
15 }QUEUE;
16
17 void init(QUEUE *pQ);
18 int en_queue(QUEUE *pQ , int val);
19 void traverse_queue(QUEUE *pQ);
20 int out_queue(QUEUE *pQ , int *pVal);
21
22 int main(void)
23 {
24 QUEUE Q;
25 int val;
26
27 init(&Q);
28
29 en_queue(&Q,1);
30 en_queue(&Q,2);
31 en_queue(&Q,3);
32 en_queue(&Q,4);
33 en_queue(&Q,5);
34 en_queue(&Q,6);
35 en_queue(&Q,7);
36 en_queue(&Q,8);
37
38 traverse_queue(&Q);
39
40 if(out_queue(&Q,&val))
41 {
42 printf("出队成功,队列出队元素为 : %d\n",val);
43 }
44 else
45 {
46 printf("出队失败!");
47 }
48
49 traverse_queue(&Q);
50
51 return 0;
52 }
53
54 //循环队列的初始化
55 void init(QUEUE *pQ)
56 {
57 pQ -> pBase = (int *)malloc(sizeof(int)*6); //分配内存,数组长度为6
58
59 pQ -> front = 0;
60 pQ -> rear = 0;
61
62 return;
63 }
64
65 //判断循环队列是否为满
66 int full_queue(QUEUE *pQ)
67 {
68 if((pQ -> rear + 1) % 6 == pQ -> front)
69 {
70 return true;
71 }
72 else
73 return false;
74 }
75
76 //入队操作
77 int en_queue(QUEUE *pQ , int val)
78 {
79 if(full_queue(pQ))
80 {
81 return false;
82 }
83 else
84 {
85 pQ -> pBase[pQ -> rear] = val;
86 pQ -> rear = (pQ -> rear + 1) % 6;
87
88 return true;
89 }
90 }
91
92
93 //遍历循环队列
94 void traverse_queue(QUEUE *pQ)
95 {
96 int i = pQ -> front;
97
98 printf("遍历队列:");
99 while(i != pQ -> rear)
100 {
101 printf("%d\t", pQ -> pBase[i]);
102
103 i = (i + 1) % 6 ;
104 }
105
106 printf("\n");
107
108 return;
109 }
110
111 //判断循环队列是否为空
112 int empty_queue(QUEUE *pQ)
113 {
114 if(pQ -> front == pQ -> rear)
115 {
116 return true;
117 }
118 else
119 return false;
120 }
121
122 //循环队列的出队操作
123 int out_queue(QUEUE *pQ , int *pVal)
124 {
125 if(empty_queue(pQ))
126 {
127 return false;
128 }
129 else
130 {
131 *pVal = pQ -> pBase[pQ -> front];
132 pQ -> front = (pQ -> front + 1) % 6;
133
134 return true;
135 }
136 }

posted @ 2011-09-10 15:58  MATRIX | yan  阅读(3295)  评论(1编辑  收藏  举报