C 编程使用 FIFO 从队列中删除(先进先出)

标签 c queue

我的任务是编写添加到队列后面并从前面删除的函数。

我已经编写了添加到队列的函数:

void queue_put(Queue *q, Qitem *new_item)
{

    new_item->next = NULL;

    if (queue_empty(q)){

            q->front = new_item;

    } else {

            q->back->next = new_item;
    }

    q->back = new_item;

}

这工作正常,但我正在努力编写从队列前面删除的函数:

Qitem * queue_get(Queue *q)
{
    if (queue_empty(q)) {

            return (Qitem *)0;

    } else {

            Qitem front_item = q->front;
            q->front = q->front->next;
            return front_item;
    } 

}

以上是我最好的尝试,但它不起作用,我想知道是否有人可以提供帮助?我意识到这可能是一个基本问题,但我对此还很陌生。

最佳答案

这个怎么样?

Qitem * queue_get(Queue *q)
{
    if (queue_empty(q)) {

            return (Qitem *)0;

    } else {

            Qitem *front_item = q->front;
            Qitem *back_item = q->back;
            q->front = q->front->next;
            if (front_item == back_item) {
               q->back = NULL; // single element
            }
            return front_item;
    } 
}

关于C 编程使用 FIFO 从队列中删除(先进先出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26505539/

相关文章:

python - 存储代码以供以后执行的最佳方式(python)

c - `while (1)` 的替代品以简化分支

c - 使用带有线程的 C 套接字来读取和写入套接字时出现问题

c - 我的指针初始化错误吗?

linux - 队列的实现给出运行时错误

c - 为什么我的循环仅适用于前几次迭代?

php - 有没有办法在 Symfony 4 中放置队列 worker ?

c - 将现有 C Code::Blocks 项目实现为 DLL

c - 为什么 vector 长度 SIMD 代码比普通 C 慢

java - 在 gs-collections 库中寻找排序堆和并发队列