zoukankan      html  css  js  c++  java
  • 队列与循环队列

    复习一下队列与循环队列的实现(C语言)

    1、单链队列:

     1 typedef struct QNode{ //若不写typedef,在C中每次定义QNode需要在前面加上struct,而C++不必
     2     QElemType data;
     3     struct QNode *next;
     4 }QNode,*QueuePtr;
     5 
     6 typedef struct{ //若不写结构体名,则需要加上typedef
     7     QueuePtr front;
     8     QueuePtr rear;
     9 }LinkQueue;
    10 
    11 status InitQueue(LinkQueue &Q){  //初始化
    12     Q.front = Q.rear = (QueuePtr) malloc(sizeof(QNode));
    13     if(!Q.front)
    14         exit(OVERFLOW);
    15     Q.front -> next = NULL;
    16     return OK;
    17 }
    18 
    19 status EnQueue(LinkQueue &Q,QElemType &e){  //把元素e入队
    20     p = (QueuePtr) malloc(sizeof(QNode));
    21     if(!p)
    22         exit(OVERFLOW);
    23     p -> next = NULL;
    24     p -> data = e;
    25     Q.rear -> next = p;
    26     Q.rear = p;
    27     return OK;
    28 }
    29 
    30 status Dequeue(LinkQueue &Q,QElemType &e){  //删除对头元素,且把队顶元素保存在e中
    31     if(Q.front == Q.rear)
    32         return ERROR;
    33     p = Q.front -> next;
    34     e = p -> data;
    35     Q.front -> next = p -> next;
    36     if(Q.rear == p)
    37         Q.rear = Q.front;
    38     free(p);
    39     return OK;
    40 }

    2、循环队列

     1 #define MAXQSIZE 100
     2 
     3 typedef struct{
     4     QElemType *base;
     5     int front;
     6     int rear;
     7 }SqQueue;
     8 
     9 status InitQueue(SqQueue &Q){
    10     Q.base = (QElemType *) malloc(MAXQSIZE*sizeof(QElemType));
    11     if(!Q.base)
    12         exit(OVERFLOW);
    13     Q.front = Q.rear = 0;
    14     return OK;
    15 }
    16 
    17 status EnQueue(SqQueue &Q,QElemType &e){
    18     if((Q.rear+1)%MAXQSIZE == Q.front)  //队列已满
    19         return ERROR;
    20     Q.base[Q.rear] = e;
    21     Q.rear = (Q.rear+1)%MAXQSIZE;
    22     return OK;
    23 }
    24 
    25 status Dequeue(SqQueue &Q,QElemType &e){
    26     if(Q.front == Q.rear)
    27         return ERROR;
    28     e = Q.base[Q.front];
    29     Q.front = (Q.front+1)%MAXQSIZE;
    30     return OK;
    31 }
  • 相关阅读:
    禅道开源版本安装
    NATAPP内网穿透实现
    nginx部署前端项目
    docker-compose部署微服务
    python编写猜数字游戏
    Linux命令(用户管理、组和时间管理)
    Linux命令(文本编辑器)
    Linux的简单命令(防火墙篇)
    什么是泛型
    spring bean 的作用域之间有什么区别
  • 原文地址:https://www.cnblogs.com/pngcui/p/4415749.html
Copyright © 2011-2022 走看看