将结构链接列表转换为C中的FIFO

时间:2018-06-27 15:28:24

标签: 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,而且我似乎无法使其正常工作。

1 个答案:

答案 0 :(得分:1)

您现有的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;
}