I am looking at the following paragraph in the book “Programming Interviews Exposed” in reference to the implementation of a linked list stack in C:
typedef struct Element {
struct Element *next;
void *data;
} Element;
void push( Element *stack, void *data );
void *pop( Element *stack );
Now consider what will happen in these routines in terms of proper
functionality and error handling. Both operations change the first
element of the list. The calling routine’s stack pointer must be
modified to reflect this change, but any change you make to the
pointer that is passed to these functions won’t be propagated back to
the calling routine. You can solve this problem by having both
routines take a pointer to a pointer to the stack. This way, you can
change the calling routine’s pointer so that it continues to point at
the first element of the list. Implementing this change results in the
following:
void push( Element **stack, void *data );
void *pop( Element **stack);
Could someone explain, in different words, why we need to use a double pointer here? I’m a bit unsure about the explanation provided.
It is similar to the famous swap() function in C.
Case 1:
Case 2:
and we invoke swap like this:
Case 1:
Case 2:
Remember, we wanted to CHANGE the values of x and y. For CHANGING values of a datatype, we need pointers. Take this to the next level for pointers. For CHANGING values of a pointer, we would need double pointers.
For Stack using linked list:
If you push values 10, 20 and 30, they are stored like this:
So you see every time you push or pop values from the stack, which is a linked list, the top or the first node of the linked list changes. Hence you need double pointers.