您的位置:首页 > 编程语言

队列中入队,出队,遍历算法代码演示

2014-03-08 14:22 639 查看
#include <stdio.h>
#include <stdlib.h>

typedef struct STR{
int * Pbase;
int front;
int rear;
}QUEUE,*pQueue;
void init(pQueue);
int en_queue(pQueue,int);
int IS_empty(QUEUE);
int IS_full(QUEUE);
int out_queue(pQueue,int*);     //第二个参数,记录出队的元素地址
void traverseQueue(QUEUE);
int len = 6;            //定义数组的长度

int main(int argc, const char * argv[])
{
QUEUE queue;
int val = 0;
init(&queue);
en_queue(&queue,2);
en_queue(&queue, 8);
en_queue(&queue, 8);
en_queue(&queue, 8);
en_queue(&queue, 8);

out_queue(&queue, &val);
printf("出队成员是:%d \n",val);
out_queue(&queue, &val);
printf("出队成员是:%d \n",val);
out_queue(&queue, &val);
printf("出队成员是:%d \n",val);
en_queue(&queue, 4);
en_queue(&queue, 8);

traverseQueue(queue);
return 0;
}

void init(pQueue Pque){
Pque->Pbase = (int*)malloc(sizeof(int)*len);
Pque->front = 0;
Pque->rear = 0;
}
int IS_empty(QUEUE queue){
if (queue.rear == queue.front) {
printf("队列为空!\n");
return 0;
}
else
return 1;
}
int IS_full(QUEUE queue){
if ((queue.rear+1)%len == queue.front) {
printf("该队列已满!\n");
return 0;
}
else
return 1;
}
int en_queue(pQueue Pque,int val){
if (IS_full(*Pque) ==0) {
return 0;
}
else{
Pque->Pbase[Pque->rear] = val;
Pque->rear = (Pque->rear+1)%len;  //注意入队时,rear的增加要对数组长度取余
return 1;
}
}
int out_queue(pQueue Pque,int* val){
if (IS_empty(*Pque) == 0) {
return 0;
}
else{
*val = Pque->Pbase[Pque->front];
Pque->front = (Pque->front+1)%len;
return 1;
}
}

void traverseQueue(QUEUE queue){
printf("队列成员有: ");
while (queue.front != queue.rear) {
printf("%d ",queue.Pbase[queue.front]);
queue.front = (queue.front+1)%len;    //循环队列的输出,个数加一,对长度取余
}
printf("\n");
}

注意:静态队列,一定是循环队列.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列 算法 遍历
相关文章推荐