I am just wanting a simple explanation of the linking process when pushing data onto a stack. I know how to build on using the code from my book, but I am not really sure I understand how the process works when you move the stack head link from one to the next.
For stacks like:
typedef struct node
{
void dataptr;
struct node* link;
}STRUCT_NODE;
typedef struct
{
int count;
STACK_NODE* top;
}STACK;
How do you change the link to point to the new data pushed on the stack. Also I do not know
Stacks can be implemented in various ways, but given the way you phrase your question I’m assuming your stack is just a linked list, something like
“when you move the stack head link from one to the next” the picture just changes to:
Of course A is not reachable any more in this graph, so you’d better have another pointer to it somewhere (be it only to dispose of it), but this is the gist how how the stack is popped (by making
head = head->nextif each node in the stack is astruct nodewith anextfield that’s astruct node*, and of courseheadis astruct node*as well).That’s for popping something off the stack (and you should free the memory used by
Ain that case). In detailed steps, it would be:1/ Saving the old head.
2/ Adjusting the head.
3/ Returning the old head (pointed at by
old).If instead you’re talking about pushing something onto the stack, that’s an operation that involves:
1/ Creating a new element.
2/ Pointing it towards the current head
3/ Adjusting the head to point to it.