链队列

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct {
    int id;
}ElemType;
typedef struct st{
    ElemType data;
    struct st *next;
}LinkNode;
/*
 *
 *
 * 根据自己的需求修改数据结构
 * 不要把眼光局限在课本里面
 *
 *
 *
 *
 *
 * */
typedef struct {
    LinkNode *front,*rear;//带头结点中,front指向头结点,rear指向尾结点
}LinkQueue;//链表中,表示一个链表只需要一个LNode表示,而在队列中,表示一个队列则需要队首和队尾指针两个来表示一个队列
void InitQueue(LinkQueue *Q);
bool Empty(LinkQueue *Q);
void InitQueue1(LinkQueue *Q);
bool Empty1(LinkQueue *Q);
bool DeQueue(LinkQueue *Q,ElemType *x);
void EnQueue(LinkQueue *Q,ElemType x);
bool DeQueue1(LinkQueue *Q,ElemType *x);
void EnQueue1(LinkQueue *Q,ElemType x);

int main(){
    ElemType a={1},b={2},c={3};
    LinkQueue *Q = (LinkQueue *) malloc(sizeof(LinkQueue));
    InitQueue1(Q);
    Empty1(Q);
    EnQueue1(Q,a);
    EnQueue1(Q,b);
    DeQueue1(Q,&c);
    return 0;
}

//以下是带头结点
bool DeQueue(LinkQueue *Q,ElemType *x){
    if(Empty(Q))
        return false;
    LinkNode *p=Q->front->next;//front指向的是队列头,front的next指向的才是需要出栈的那个。p指向要被删除的结点
    *x=p->data;
    Q->front->next=p->next;
    if(Q->rear==p)//此次是最后一个结点出队
        Q->rear=Q->front;//修改rear的指针,如果不这样做,rear的指针将为Null,而front指针为头结点,不满足判定条件
    free(p);//释放结点空间
}
void EnQueue(LinkQueue *Q,ElemType x){
    LinkNode *s = (LinkNode *) malloc(sizeof(LinkNode));
    s->data = x;
    s->next=NULL;//由于只能添加到队尾,因此,next必定是null
    Q->rear->next=s;
    Q->rear=s;//更新rear
}
void InitQueue(LinkQueue *Q){//Q不再是和LinkNode等价的东西了,现在Q是一个队列
    Q->front=Q->rear=(LinkNode *)malloc(sizeof(LinkNode));
    Q->front->next=NULL;
}

bool Empty(LinkQueue *Q){
    if(Q->front->next==NULL)
        return true;
    else
        return false;
}

//以下是不带头结点
bool DeQueue1(LinkQueue *Q,ElemType *x){
    if(Empty1(Q))
        return false;
    LinkNode *p=Q->front;
    *x=p->data;
    Q->front=p->next;
    if(Q->rear==p)//此次是最后一个结点出队
        Q->rear=Q->front=NULL;//这一片被free之后,front和rear指向的都是一片脏数据,而不是NULL
    free(p);//释放结点空间
}
void EnQueue1(LinkQueue *Q,ElemType x){
    LinkNode *s = (LinkNode *) malloc(sizeof(LinkNode));
    s->data = x;
    s->next=NULL;//由于只能添加到队尾,因此,next必定是null
    if(Q->front==NULL){
        Q->front=s;
        Q->rear=s;
    } else {
        Q->rear->next=s;
        Q->rear=s;
    }
}

void InitQueue1(LinkQueue *Q){
    Q->front=Q->rear=NULL;
}

bool Empty1(LinkQueue *Q){
    if(Q->front==NULL)
        return true;
    else
        return false;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值