队列(C语言)

顺序结构

typedef struct{
    int* data;
    int front,rear;
    int maxsize;
}Squeue,*Queue;

循环队列

顺序结构

typedef int ElemType;   //ElemType的类型根据实际情况而定,这里假定为int
#define MAXSIZE 50  //定义元素的最大个数
/*循环队列的顺序存储结构*/
typedef struct{
    ElemType data[MAXSIZE];
    int front;  //头指针
    int rear;   //尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;

(1)初始化

Queue init(int maxsize){
    Queue Q=(Queue)malloc(sizeof(Squeue));
    Q->data=(int*)malloc(sizeof(int));
    Q->front=0;
    Q->rear=0;
    Q->maxsize=maxsize; 
    return Q;
}

(2)判队空

bool isempty(Queue Q){
    if(Q->rear==Q->front){
        return true;
    }
    else{
        return false;
    }
}

(3)求长度

/*返回Q的元素个数,也就是队列的当前长度*/
int QueueLength(SqQueue Q){
    return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}

(4)入队

Queue Add(Queue Q,int e){
    if(isempty(Q)){
        printf("队列空");
        return ERROR;
    }
    else{
        Q->data[Q->rear]=e;
        Q->rear=(Q->rear+1)%Q->maxsize;
        return Q;
    }
}

(5)出队

/*若队列不空,则删除Q中队头元素,用e返回其值*/
Status DeQueue(SqQueue *Q, ElemType *e){
    if(isEmpty(Q)){
        return REEOR;   //队列空的判断
    }
    *e = Q->data[Q->front]; //将队头元素赋值给e
    Q->front = (Q->front + 1) % MAXSIZE;    //front指针向后移一位置,若到最后则转到数组头部
}

(6)删除节点

BTree Delete(Queue Q){
        BTree front=Q->data[Q->front];
        Q->front=(Q->front+1)%Q->maxsize;
        return front;
}

链式结构

/*链式队列结点*/
typedef struct {
    ElemType data;
    struct LinkNode *next;
}LinkNode;
/*链式队列*/
typedef struct{
    LinkNode *front, *rear; //队列的队头和队尾指针
}LinkQueue;

(1)初始化

void InitQueue(LinkQueue *Q){
    Q->front = Q->rear = (LinkNode)malloc(sizeof(LinkNode));    //建立头结点
    Q->front->next = NULL;  //初始为空
}

(2)入队

Status EnQueue(LinkQueue *Q, ElemType e){
    LinkNode s = (LinkNode)malloc(sizeof(LinkNode));
    s->data = e;
    s->next = NULL;
    Q->rear->next = s;  //把拥有元素e新结点s赋值给原队尾结点的后继
    Q->rear = s;    //把当前的s设置为新的队尾结点
    return OK;
}

(3)出队

/*若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR*/
Status DeQueue(LinkQueue *Q, Elemtype *e){
    LinkNode p;
    if(Q->front == Q->rear){
        return ERROR;
    }
    p = Q->front->next; //将欲删除的队头结点暂存给p
    *e = p->data;   //将欲删除的队头结点的值赋值给e
    Q->front->next = p->next;   //将原队头结点的后继赋值给头结点后继
    //若删除的队头是队尾,则删除后将rear指向头结点
    if(Q->rear == p){   
        Q->rear = Q->front;
    }
    free(p);
    return OK;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值