我使用 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/