在C中将结构链表转换为FIFO

Converting struct linked list to FIFO in C

我正在使用 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;
}