【队列】

【队列】

顺序队列

如果不采用循环队列的方式,很多空间会被浪费掉,效率低,因此使用循环队列。

循环队列:

  • 头指针:第一个元素
  • 尾指针:最后一个元素的下一个元素
  • 判空:front == rear
  • 判满:front == (rear + 1) % MaxSize
  • 入队尾后移:rear = (rear + 1) % MaxSize
  • 出队头后移:front = (front + 1) % MaxSize

1.实现

typedef struct QNode *Queue;
struct QNode {
    ElementType Data[MaxSize];
    int Front,Rear; // 头尾指针,头指向队列首元素,尾指向队列最后一个元素的下一位置
};

2.建立空队列

Queun CreateQueue()
{
    Queue Q = (Queue)malloc(sizeof(struct QNode));
    Q -> Front = Q -> Rear = 0;
    return Q;
}

3.入队

void AddQ(Queue Q,ElementType e)
{
    if(IsFull(Q))
        return;
    else {
   		Q -> Data[Q -> Rear] = e;
        Q -> Rear = (Q -> Rear + 1) % Maxsize;
    }
}

4.出队

ElementType DeleteQ(Queue Q)
{
    if(IsEmpty(Q))
        return;
    else {
        Q -> Front = (Q -> Front + 1) % MaxSize;
        return Q -> Data[Q -> Front - 1];
    }
}

5.判空

int IsEmpty(Queue Q)
{
    return(Q -> Front == Q -> Rear);
}

6.判满

int IsFull(Queue Q)
{
    return(Q -> Front == (Q -> Rear + 1) % MaxSize);
}
链式队列
  • 头指针:第一个元素
  • 尾指针:最后一个元素
  • 判空:front =NULL rear == NULL

1.实现

typedef struct Node *QNode;
struct Node {
    ElementType Data;
    QNode Next;
}

typedef struct Que *Queue;
struct Que {
    QNode Front,Rear;
}

2.通过给定元素建立一个队列

// 通过给定的元素建立一个队列
Queue CreateQueue(ElementType e)
{
    Queue Q;
    QNode QN;
    Q = (Queue)malloc(sizeof(struct Que));
    QN = (QNode)malloc(sizeof(struct Node));
    Q -> Front = Q -> Rear = QN;
    QN -> Data = e;
    QN -> Next = NULL;
    return Q;
}

3.入队

void AddQ(Queue Q,ElementType e)
{
    QNode QN;
    QN = (QNode)malloc(sizeof(struct Node));
    QN -> Data = e;
    QN -> Next = NULL;
    // 注意需要判空,因为当对空队列做入队操作时,需要将头指针指向该元素
    if(IsEmpty(Q)) {
        Q -> Front = Q -> Rear = QN;
    }
    else {
        Q -> Rear -> Next  = QN;
        Q -> Rear = QN;
    }
}

4.出队

ElementType DeleteQ(Queue Q)
{
    ElementType data; // 放置要出队的元素的值
    QNode QN; // 放置要出队的元素结点
    if(IsEmpty(Q))
        return;
    if(Q -> Front == Q -> Rear && Q -> Front != NULL) { // 队列中只有一个元素
        data = Q -> Front -> Data;
        QN = Q -> Front;
        free(QN);
        Q -> Front = Q -> Rear = NULL; // 将队列设置为空
    }
    else {
        data = Q -> Front -> Data;
        QN = Q -> Front;
        free(QN);
        Q -> Front = Q -> Front -> Next;
    }
    return data;
}

5.判空

int IsEmpty(Queue Q)
{
    return(Q -> Front == Q -> Rear && Q -> Front == NULL);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百栗.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值