Reputation: 1713
I'm using an example provided by Havenard as an answer to this question: 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
It worked well for my purpose, but now things have changed and I would now prefer it to use FIFO rather than LIFO and I can't seem to get it to work.
Upvotes: 0
Views: 201
Reputation: 50077
Your existing LIFO pop_stack
routine needs to be rewritten for 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;
}
Upvotes: 1