• 3.3 循环队列


    // 循环队列采用顺序存储,为了区分队头和队尾,从1号下标开始存储
    // 队头队尾同时指向0号下标表示队空,队尾下标的下一个元素是队头的时候表示队满
    // 可以设置front指向队头元素,rear指向队尾元素的下一个位置
    // 或者设置front指向队头元素的下一个节点,rear指向队尾元素
    // 本程序采用前一种,后一种在操作的时候略有不便
    // 出队的时候front+1,入队的时候rear+1
    
    /*补充求队长*/
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAXSIZE 6 
    
    typedef struct node{
        int data[MAXSIZE];           // 0号下标的元素空出来作为头节点
        int front,rear;
    }Queue;
    
    void initQueue(Queue *Q){
        Q->front=0;
        Q->rear=0;
    }
    
    int isEmpty(Queue *Q){
        if(Q->front==Q->rear) 
            return 1;
        return 0;
    }
    
    int isFull(Queue *Q){
        if(Q->front==(Q->rear+1)%MAXSIZE) return 1;
        return 0;
    }
    
    int enQueue(Queue *Q, int e){
        if(isFull(Q)){
            return 0;           // 判满
            puts("Full!");
        }
        Q->rear=(Q->rear+1)%MAXSIZE;
        Q->data[Q->rear]=e;
        return 1;
    }
    
    int deQueue(Queue *Q,int *e){
        if(isEmpty(Q)){
            puts("Empty!"); 
            return 0;
        }
        *e=Q->data[Q->front+1];    // +1跳过头节点
        Q->front=(Q->front+1)%MAXSIZE;
        return 1;
    }
    
    int QueueLength(Queue Q){
        return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
    }
    
    
    // 用idx暂时代替front,判断条件不变
    void disp(Queue Q){
        int idx=Q.front;     // 未出队时,front默认为0
        while(idx%MAXSIZE!=Q.rear){
            printf("%d ",Q.data[++idx]);
        }
    }
    
    int  main(){
        Queue Q;
        initQueue(&Q);
        enQueue(&Q,7);
        enQueue(&Q,4);
        enQueue(&Q,2);
        enQueue(&Q,3);
        enQueue(&Q,6);
        int e;
        deQueue(&Q,&e);
        disp(Q); printf("
    Length:%d",QueueLength(Q));
        printf("
    e:%d
    ",e);
        deQueue(&Q,&e);
        deQueue(&Q,&e);
        deQueue(&Q,&e);
        deQueue(&Q,&e);
    
        deQueue(&Q,&e); //Empty
        
    }
  • 相关阅读:
    python-变量
    Python-编码
    Linux中 set、env、declare、export显示shell变量的区别
    iOS 为移动中的UIView(UIButton )添加点击事件
    iOS 8 TabBar 图片显示真实颜色
    Error Domain=ASIHTTPRequestErrorDomain Code=8 "Failed to move file from"xxx/xxx"to"xxx/xxx"
    iOS 判断View 是否是第一次显示
    编写程序时的注意事项
    iOS 图片填充 UIImageView (contentMode)
    修改 UISearchBar cancelButton 样式
  • 原文地址:https://www.cnblogs.com/Alexagender/p/10806309.html
Copyright © 2020-2023  润新知