C 中结构体链表转换为 FIFO

标签 c struct fifo

我使用 Havenard 提供的示例来回答此问题:Writing a push and pop in c

struct stack_control {
    struct stack_control* next;
    void* data;
};

void push_stack(struct stack_control** stack, void* data)
{
    struct stack_control* temp = malloc(sizeof(struct stack_control));
    temp->data = data;
    temp->next = *stack;
    *stack = temp;
}

void* pop_stack(struct stack_control** stack)
{
    void* data = NULL;
    struct stack_control* temp = *stack;
    if (temp)
    {
        data = temp->data;
        *stack = temp->next;
        free(temp);
    }
    return data;
}

struct stack_control* stack = NULL; // empty stack

它对我的目的来说效果很好,但现在情况发生了变化,我现在更喜欢它使用 FIFO 而不是 LIFO,但我似乎无法让它工作。

最佳答案

您现有的 LIFO pop_stack 例程需要针对 FIFO 进行重写:

void* pop_stack(struct stack_control** stack)
{
    void* data = NULL;
    struct stack_control *prev = NULL;
    struct stack_control *last = *stack;

    while(last->next != NULL)
      {
      prev = last;
      last = last->next;
      }

    if (last)
    {
        data = last->data;
        free(last);

        if(prev)
          prev->next = NULL;
    }

    return data;
}

关于C 中结构体链表转换为 FIFO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51066526/

相关文章:

c - 需要帮助理解枚举和数组

c - 用于数组和标量的 Fortran 到 C 接口(interface)

c - 有关子进程终止的更多信息?

c - 我应该使用什么类型才能获得最快的计算速度?

json - 在 golang 中持久化嵌套结构

比较 C 中的两个变量

algorithm - LRU vs FIFO vs 随机

c++ - 好或坏 : to make giant struct to avoid using globals/properties of a struct/lots of paramerters

c - 具有 FIFO 的 Posix 信号量无法正常工作

java - 具有有限元素的 FIFO 映射