队列

队列的定义与操作(first in,first out)

1.顺序存储:

在该方式中,队列由一个结构体构成,其中结构体包含:一个数组(定长),队列头尾标识和最大容量。由此可知顺序存储的队列长度有限,下面会介绍链式存储队列(长度不限)。

在顺序存储队列中,若用普通数组:在这里插入图片描述如图所示,会出现队列有空位而无法入队的情况,因而采用另外一种方式:
在这里插入图片描述
即循环队列,只要队列有空位即可入队,但由此而来的问题是,当队列满和队列空时,front和rear都会相等,有两种解决方式:

  1. 加一个标志量flag,初始为0,每次入队改为1,出队为0;
  2. 当队列只剩一个位置时,视为队列满;

下面采用第二种方式进行代码实现:

struct queue_list{
    elementtype data[max];//存放数据数组
    int front;//列首位置
    int rear;//列末位置
    int max;//队列最大容量
}
typedef struct queue_list* queue;

//初始化队列
queue initial(int max){
    queue q=(queue)malloc(sizeof(struct queue_list));
    q->max=max;
    q->front=q->rear=0;
    return q;
}

//判断队列是否满
bool isfull(queue q){
    return ( (q->rear+1)%(q->max)==q->max );
}

//元素x入队
bool add(queue q,elementtype x){
    if (isfull(q))
        return false;//队列满
    else{
        q->rear=(q->rear+1)%(q->max);
        q->data[q->rear]=x;
        return true;//入队成功
    }
}

//判断队列是否为空
bool isempty(queue q){
    return (q->front==q->rear);
}

//出队
elementtype delete(queue q){
    if (isempty(q))
        return false;//队列空
    else{
        q->front=(q->front+1)%(q->max);
        return q->data[q->front];//出队成功
    }
}

2.链式存储:

typedef struct queue_chain* queue;
struct queue_chain{//队列中每个成员组成成分
    elementtype data;
    queue next;
}
struct chain_flag{
    queue front;//列首指针
    queue rear;//列末指针
    int size;//队列当前长度
}
typedef struct chain_flag* chain;

//初始化
chain initial(){
    chain q=(chain)malloc(sizeof(struct chain_flag));
    q->front=q->rear=null;
    q->size=0;
    return q;
}

//判断队列是否空
bool isempty(chain q){
    return (q->front==null);
}

//入队
bool add(chain q,elementtype x){
    //因链式队列无长度限制,无需判断队列是否满,但要判断队列是否为空
    if (isempty(q)){
        //当队列为空时,需将front和rear都指向这第一个成员,然后将成员的next置为空
        q->front=q->rear=(queue)malloc(sizeof(struct queue_chain));
        q->front->data=x;
        q->front->next=null;
        q->size++;
        return true;
    }
    else{//队列不为空
        queue temp=(queue)malloc(sizeof(struct queue_chain));
        temp->data=x;
        q->rear->next=temp;
        temp->next=null;
        q->rear=temp;
        q->size++;
        return true;
    }
}

//出队
elementtype delete(chain q){
    //队列空
    if (isempty(q))
        return false;
    //队列不为空
    else{
        elementtype temp=q->front->data;//存放出队成员的值x
        queue temp_ptr=q->front;//存放出队成员的指针
        if (q->size==1)	//队列仅剩一个成员
            q->front=q->rear=null;
        else			//队列成员数大于一
            q->front=temp_ptr->next;
        free(temp_ptr);
        return temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值