I am implementing a stack using linked list in C, and I stumbled upon two issues:
I need the stack_pop
function to return a valid value temp
, that is the temporary node/cell, and therefore, I can't free it. So, 1) Do you think freeing each node for every pop function call is better than until the end using the stack_destroy()
2) How can I achieve both, free(temp)
and return it at the same time in stack_pop
?
How bad my implementation becomes not using exit(1)
in both stack_push
and stack_pop
functions?
This is the implementation:
//// Stack
// Linked list
typedef struct {
int data;
Cell* next;
} Cell;
struct stack_l {
size_t count;
Cell *top;
};
typedef struct stack_l *Stack;
dbush :
You've got stack_pop declared to return an int, but you're attempting to return a Cell * which doesn't make sense.\nCopy the value in the popped cell to a local variable, free the popped cell, then return the value.\n temp = stack->top;\n stack->top = stack->top->next;\n temp->next = NULL;\n stack->count--;\n int val = temp.data;\n free(temp)\n return val;\n\nAlso, it makes no sense to call exit in either stack_push or stack_pop as that ends the program.",
2021-10-01T15:50:54