置空队算法:

  1. 将队尾指针指向头结点;
  2. 将头结点的指针域指向自身。
void clearQueue() {
    rear = front = head;
    head->next = head;
}

判队空算法:

队列为空当且仅当队头和队尾指针相等且指向头结点。

bool isEmpty() {
    return rear == front && rear == head;
}

入队算法:

  1. 创建新节点;
  2. 将新节点插入到队尾;
  3. 修改队尾指针。
void enqueue(elemType x) {
    node* newNode = new node(x);
    newNode->next = rear->next;
    rear->next = newNode;
    rear = newNode;
}

出队算法:

  1. 如果队列为空,则返回一个特定值;
  2. 将队头元素保存到临时变量中;
  3. 删除队头元素;
  4. 修改队头指针。
elemType dequeue() {
    if (isEmpty()) {
        // 队列为空,返回一个特定值
        return NULL;
    }
    elemType res = front->next->data;
    node* temp = front->next;
    front->next = front->next->next;
    if (rear == temp) {
        rear = front;
    }
    delete temp;
    return res;
}
``
假设以带头结点的循环链表表示队列并且只设一个指针指向队尾元素站点注意不设头指针 试编写相应的置空队、判队空 、入队和出队等算法。

原文地址: https://www.cveoy.top/t/topic/cjAu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录