数据结构-c语言代码实现-顺序队列的基本操作

动态分配顺序存储结构

#define Max 10
#define ElemType char

int flag=0;
typedef struct{
    ElemType *Data;
    int front,rear;
}QueueSq;

基本操作

  1. 初始化

void QueueSq_Init(QueueSq &Q){
    Q.Data=(ElemType *)malloc(sizeof(ElemType)*Max);
    Q.front=Q.rear =0;
}
  1. 创建队

void QueueSq_Creat(QueueSq &Q){
    if(flag==1&&Q.front ==Q.rear){
        printf("创建队失败\n");
    }
    flag==1;
    printf("请输入队列成员个数\n");
    int num=0;
    scanf("%d",&num);
    getchar();
    while(Q.rear<num){    
        printf("请输入入队成员%d:\n",Q.rear+1);
        scanf("%c",&Q.Data[Q.rear]);
        getchar();
        Q.rear=(Q.rear+1)%Max;
    }
}
  1. 入队

void QueueSq_Push(QueueSq &Q,ElemType newval){
    if(flag==1&&Q.front ==Q.rear ){
        printf("队满 入队失败\n");
        exit(-1);
    }
    else{
        flag=1;
        Q.Data[Q.rear]=newval;
        Q.rear=(Q.rear+1)%Max;
        printf("入队成功\n");
    }
}
  1. 出队

void QueueSq_Pop(QueueSq &Q,ElemType &x){
    if(flag==0&&Q.front==Q.rear ){
        printf("队空,出队失败\n");
        exit(-1);
    }
    else{
        flag=0;
        x=Q.Data[Q.front];
        Q.front=(Q.front+1)%Max;
        printf("出队成功\n");
    }
}
  1. 读取队头元素

ElemType QueueSq_GetTopval(QueueSq Q){
    if(flag==0&&Q.front==Q.rear ){
        printf("队空,读取队头元素失败\n");
    }
    else{
        printf("读取队头元素成功\n");
        return Q.Data[Q.front];
    }
} 
  1. 求队列长度

int QueueSq_Length(QueueSq Q){
    return (Q.rear-Q.front+Max)%Max;
}
  1. 打印队列

void QueueSq_Print(QueueSq Q){
    printf("队列:");
    while(Q.front!=Q.rear){
        printf("%c ",Q.Data[Q.front]);
        Q.front=(Q.front+1)%Max;
    }
    printf("\n");
}

代码实现结果

int main()
{
    QueueSq Q;
    QueueSq_Init(Q);
    QueueSq_Creat(Q);
    QueueSq_Print(Q);
    ElemType x1;
    QueueSq_Pop(Q,x1);
    QueueSq_Print(Q);
    QueueSq_Push(Q,x1);
    printf("队列长度为:%d\n",QueueSq_Length(Q));
    QueueSq_Print(Q);
}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值