数据结构之队列的基本操作(链式存储和顺序存储)c语言版


#include<stdio.h>
#include<stdbool.h>

#define MaxSize 50
#define  ElemType char

typedef struct{
    ElemType data[MaxSize];
    int front,rear;
}SqQueue;


//链式结构
typedef struct{
    ElemType data;
    struct LinkNode *next;
}LinkNode;

typedef struct{
    LinkNode *front,*rear;
}LinkQueue;

//以下为循环队列的基本操作
//顺序存储的队列初始化
void InitQueue(SqQueue *Q){
    Q->rear = Q->front = 0;
}

//链式队列初始化
void InitLinkQueue(LinkQueue *Q){
    Q->front = (LinkNode*)malloc(sizeof(LinkNode));
    Q->rear = Q->front;
    Q->front->next = NULL;
}

bool isEmpty(SqQueue Q){
    if(Q.rear == Q.front)
        return true;
    else
        return false;
}

bool isLinkEmpty(LinkQueue Q){
    if(Q.front == Q.rear)
        return true;
    else
        return false;
}

//入队
bool EnQueue(SqQueue *Q,ElemType x){
    if((Q->rear+1)%MaxSize == Q->front)
        return false;
    Q->data[Q->rear] = x;
    Q->rear = (Q->rear + 1) % MaxSize;
    return false;
}

//链式队列入队
void EnLinkQueue(LinkQueue *Q,ElemType x){
    LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
    s->data = x;
    s->next = NULL;
    Q->rear->next = s;
    Q->rear = s;
}

//出队
bool DeQueue(SqQueue *Q,ElemType *x){
    if(Q->rear == Q->front)
        return false;
    *x = Q->data[Q->front];
    Q->front = (Q->front + 1) % MaxSize;
    return true;
}

//链式表出队
bool DeLinkQueue(LinkQueue *Q,ElemType *x){
    if(Q->front == Q->rear)
        return false;
    LinkNode *p = Q->front->next;
    *x = p->data;
    Q->front->next = p->next;
    if(Q->rear == p)
        Q->rear = Q->front;
    free(p);
    return true;
}


void QueuePrintf(SqQueue Q){
    ElemType x;
    while(!isEmpty(Q)){
        DeQueue(&Q,&x);
        printf("%c",x);
    }
}

void QueueLinkPrintf(LinkQueue Q){
    ElemType x;
    while(!isLinkEmpty(Q)){
        DeLinkQueue(&Q,&x);
        printf("%c",x);
    }
}

int main(){
    SqQueue sq;
    LinkQueue linkSq;
    ElemType c;
    InitQueue(&sq);
    printf("建立顺序存储的队列");
    printf("请输入要入队的元素回车,以'0'结束\n");
    scanf("%c",&c);
    while(c != '0'){
        EnQueue(&sq,c);
        scanf("%c",&c);
    }
    printf("您建立的队列为:\n");
    QueuePrintf(sq);

    //链式队列初始化
    InitLinkQueue(&linkSq);
    printf("建立链式存储的队列");
    printf("请输入要入队的元素回车,以'0'结束\n");
    scanf("%c",&c);
    while(c != '0'){
        EnLinkQueue(&linkSq,c);
        scanf("%c",&c);
    }
    printf("您建立的链式队列为:");
    QueueLinkPrintf(linkSq);

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值