zoukankan      html  css  js  c++  java
  • [算法] 队列

    循环队列

    一、顺序存储

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 typedef int ElementType;
     4 typedef int Position;
     5 typedef struct QNode * PtrToQNode;
     6 struct QNode{
     7     ElementType * Data;
     8     Position Front,Rear;
     9     int MaxSize;
    10 };
    11 typedef PtrToQNode Queue;
    12 //创建队列 
    13 Queue CreateQueue(int MaxSize){
    14     Queue Q = (Queue)malloc(sizeof(struct QNode));
    15     Q->Data = (ElementType*)malloc(MaxSize*sizeof(ElementType));
    16     Q->Front=Q->Rear=0;
    17     Q->MaxSize=MaxSize;
    18     return Q;
    19 } 
    20 bool IsFull(Queue Q){
    21     return((Q->Rear+1)%Q->MaxSize==Q->Front);
    22 }
    23 //插入元素 
    24 bool AddQ(Queue Q,ElementType X){
    25     if(IsFull(Q)){
    26         printf("队列满");
    27         return false;
    28     }else{
    29         Q->Rear=(Q->Rear+1)%Q->MaxSize;
    30         Q->Data[Q->Rear]=X;
    31         return true;
    32     }
    33 }
    34 bool IsEmpty(Queue Q){
    35     return(Q->Front==Q->Rear);
    36 }
    37 //删除元素 
    38 ElementType DeleteQ(Queue Q){
    39     if(IsEmpty(Q)){
    40         printf("队列空");
    41         return -1;
    42     }else{
    43         Q->Front=(Q->Front+1)%Q->MaxSize;
    44         return Q->Data[Q->Front];
    45     }
    46 }
    47 int main(){
    48     Queue que;
    49     que=CreateQueue(5);
    50     AddQ(que,10);
    51     AddQ(que,20);
    52     AddQ(que,30);
    53     printf("%d",DeleteQ(que));
    54     printf("%d",DeleteQ(que));
    55     printf("%d",DeleteQ(que));
    56 }

    分析:

    1、定义结构:数据Data[];头尾结点Front、Rear;容量MaxSize

    2、创建:为队列结构和数据申请空间,数据通过结构中的指针访问;头尾指针归零

    3、插入删除:判断空满;尾入头出

    4、注意是循环队列,空满判断条件要取余

  • 相关阅读:
    day14: 生成器进阶
    day13: 迭代器和生成器
    day12:装饰器的进阶
    day11:装饰器
    day10:函数进阶
    English class 81:How Vulnerability can make our lives better?
    piano class 12
    UE4之循环
    UE4之数组
    UE4中常见的类
  • 原文地址:https://www.cnblogs.com/cxc1357/p/10807059.html
Copyright © 2011-2022 走看看