I'm trying to delete nodes from a simply linked list on C, when I delete any other node except the first it works fine, but when I try to delete the first node the whole list messes up, I've tried different solutions and I have the same outcome, I don't know what to do anymore
One of my tries was this:
void deleteClient (client **p, int n){
client *t = *p;
if (t){
while (t && t->id != n)
t = t->next;
if (t){
client * ax = t;
t = t->next;
free(ax);
}
}
}
The other one was this
void deleteClient (client **p, int n){
client *t = *p;
if (t)
if (t->id == n){
client * ax = *p;
*p = (*p)->next;
free(ax);
return;
}
else{
while (t->next && t->next->id != n)
t = t->next;
if (t->next){
client * ax = t->next;
t->next = t->next->next;
free(ax);
}
}
}
But in both versions of the code it only deletes fine from the second node onwards, while messing up the whole list if I try to delete the first node.
You can eliminate testing for multiple cases (is node the 1st, if not the 1st, etc..) by simply using a pointer-to-pointer to node to hold the current node and a pointer to the next node, e.g.
/** delete node with value n from list (for loop) */
void deleteClient (client **p, int n)
{
client **ppn = p; /* pointer to pointer to node*/
client *pn = *p; /* pointer to node */
for (; pn; ppn = &pn->next, pn = pn->next) {
if (pn->id == n) {
*ppn = pn->next; /* set address to next */
free (pn);
break;
}
}
}
This approach is detailed in Linus on Understanding Pointers
The first question that comes to me, when dealing with your problem is: If you have defined an interface to your function that receives a pointer to a client by reference, why don't you get profit from that fact and use it to modify the received pointer? (I was astonished about this, because the first thing you do, in the function is to dereference it, and use a normal pointer, and you don't touch the original pointer received anymore) If you pass a pointer to the first node, you'll never have access to the pointer variable, and you'll not be able to change its value, and so, you'll never be able to unlink the first element, and it is because of that, that you need to access the pointer pointing to the first node (in order to be able to change it). Very good at passing the pointer by reference, but bad as you didn't know why.
(pointer to 1st el.)
+-----+ +----------------+ +----------------+
--->| *p >---------->| client | next >------->| client | next >------.
+-----+ +----------------+ +----------------+ |
^ V
| NULL
+--|--+
| p | (reference to the pointer that points to the first element)
+-----+
As you move the pointer reference, you get up to this scenario:
+-----+ +----------------+ +----------------+
--->| *p >---------->| client | nxt >-------->| client | nxt >-------.
+-----+ +----------------+ +----------------+ |
^ V
,-----------------------' NULL
+--|--+
| p | (see how the reference points to the pointer, not to client node)
+-----+
From this scenario, with a reference pointed by &p, we need to make the value pointed by the pointer referenced to the next client node's nxt pointer, and not to the node itself. As here:
,---------------------------.
| |
+-----+ | +----------------+ | +----------------+
--->| *p >----' | client | nxt >-----+-->| client | nxt >-------.
+-----+ +----------------+ +----------------+ |
^ ^ =====
| | ===
+--|--+ +-|--+ =
| p | | q | (q points to the client node, instead)
+-----+ +----+
In this graph, q is a node pointer we use to link to the client node we are going in order to free() after it has been unlinked. So, your first approach can be turned into this:
void deleteClient (client **p, int n)
{
/* first advance the reference to the n-esim pointer,
* (zero meaning the first node) We decrement n after
* checking, and test goes on while *p is also non null
*/
while (*p && (*p)->id != n)
p = &(*p)->next; /* move the reference to a reference
* to the pointer in the next node. */
client *q = *p; /* temporary link to the node to be
* freed */
if (q) { /* if found */
*p = q->next; /* make *p point to the next node. */
free(q); /* free the client node */
}
}
The way to call this routine should be:
client *list;
/* ... */
deleteClient(&list, 3); /* delete node with id == 3 */
The statement p = &(*p)->next; needs some explanation:
*p is the address of the client node that the pointer referenced by p points to.
(*p)->next is the next pointer of the node the pointer referenced by p points to.
&(*p)->next is the address of that pointer.
So we make p to point to the address of the next pointer of the client node pointed to by the referenced pointer *p.
NOTE
The reason your code messes up the whole list when you delete the first node is that you make the pointer (the initial pointer to the first node) to point to the second, but that pointer is local to your function and, as you never modify the pointer passed by reference (you modify the copy you make as soon as you get into the function, it is never modified above it), it continues to point to the (now free()d) node, so this makes the mess (not only you have a pointer pointing to an invalid address, you have leaked the rest of the nodes ---as the next field of the pointed node can have been changed by free() as a result of managing the returned memory chunk---) :)
Finally, you have a complete example here, that you can checkout from github.
Related
I was iterating a tree data structure which has a pointer to its root as follows-
struct node *root;
when I have to pass reference of this root as a parameter to a function.... I have to pass it like-
calcHeight(&root);
-
-
-
//somewhere
int calcHeight(struct node **root) // function defination is this
My question is- why do we need to pass "root" pointer as &root? can't we just pass root like--
struct node *root;
calcHeight(root);
int calcHeight(struct node *root);
// EDIT
void someFunct(int *arr){
printf("arr2 inside someFunct is %d\n",arr[2]);
arr[2]=30;
}
int main()
{
int *arr=(int*)calloc(10,sizeof(int));
printf("arr[2] is %d\n",arr[2]);
someFunct(arr);
printf("arr[2] finally is %d\n",arr[2]);
return 0;
}
In this case arr in main function is modified even when I'm not passing the address of arr.
I'm getting the fact that for structures and single value vars we HAVE to pass the address like someFunct(&var) but this is not necessary for arrays? for arrays we write someFunct(arr)
But I'm not getting the reason behind this?
struct node * is a pointer to a struct node.
struct node ** is a pointer to a pointer to a struct node.
The reason for passing in a struct node ** could be that the function needs to modify what the struct node * is actually pointing at - which seems odd for a function named calcHeight. Had it been freeNode it could have made sense. Example:
void freeNode(struct node **headp) {
free(*headp);
*headp = NULL; // make the struct node * passed in point at NULL
}
Demo
Another reason could be to make the interface consistent so that one always needs to supply a struct node ** to all functions in the functions supporting struct nodes - not only those actually needing to change what the struct node * is pointing at.
Regarding the added // EDIT part:
In this scenario there is no reason to send in a pointer-to-pointer. If you do not need to change the actual pointer, you only need to send in the value of the pointer.
Example memory layout:
Address What's stored there
+-----+
| +0 | uint64_t ui1 = 1 <--+
+-----+ |
| +8 | uint64_t ui2 = 2 |
+-----+ |
| +16 | uint64_t* p = &ui1 ---+
+-----+
Now, if a function only need an uint64_t value, you can send in ui1, ui2 or *p to that function.
void someFunc(uint64_t val) { ++val; ... }
The changes this function makes to val are not visible to the caller of the function.
If a function is supposed to be able to make changes that are visible to the caller of the function, send in a pointer:
void someFunc(uint64_t *valp) { *valp = 10; }
Calling it with someFunc(&ui1); or someFunc(p); will change ui1 and assign 10 to it.
If you have a pointer and want to change what it's actually pointing at, which is what your original question was asking, you would need to send in a pointer to that pointer:
void someFunc(uint64_t **valpp) { *valpp = &ui2 }`
If you call that with someFunc(&p) (where p is currently pointing at ui1) you will find that after the function call, p will point at ui2:
+-----+
| +0 | uint64_t ui1 = 1
+-----+
| +8 | uint64_t ui2 = 2 <--+
+-----+ |
| +16 | uint64_t* p = &ui2 ---+
+-----+
Because in calcHeight you're passing your argument by value. If you want to modify the pointed value by root you need to pass the adress of the pointer.
First one is a pointer to node which is a structure.
struct node *root;
defines root as a variable which can store the address of a node.
Second one is a pointer to a pointer to node which is a structure.
struct node **root;
defines root as variable which can store address of another variable which has the address of a node.
why do we need to pass "root" pointer as &root?
calcHeight(&root);
C passes arguments by value, not by reference. so, you have to pass the address of root to modify the value of root.
I've just recently gotten into linked lists and I'm adding my own "add to end" function.
void insert_at_end(Node** head, Node* node)
{
Node* temp;
temp = *head;
if (temp == NULL) // linked list is empty
{
*head = node;
}
else
{
while (temp->pNext != NULL)
{
temp = temp->pNext;
}
temp->pNext = node;
}
}
Originally I was doing temp != NULL instead of temp->pNext != NULL because I thought that way it would take me to the very LAST node, since it stops looping when temp still has data before it reaches NULL. Wouldn't temp->pNext != NULL stop at the 2nd to last node? Since it stops looping when it realizes that the last nodes next pointer is NULL, it does not travel to that node?
Thanks guys, If I need to clear anything up from that word vomit let me know.
Wouldn't temp->pNext != NULL stop at the 2nd to last node?
No. Here is the pictorial representation for ease of understanding.
With temp != NULL, temp will be pointing to NULL:
+---+ +---+ +---+
| 1 |--->| 2 |--->| 3 |---> NULL
+---+ +---+ +---+ ^
|
temp
As you see temp is iterating until it becomes NULL, at which point you cannot attach anything to the final node because you're past it.
With temp->pNext != NULL, temp will be pointing to last node.
+---+ +---+ +---+
| 1 |--->| 2 |--->| 3 |---> NULL
+---+ +---+ +---+
^
|
temp
Here temp will iterate till its next node is NULL. That means you're pointing to the final node and you can use that pointer to adjust that node to point to a new one with temp->pNext = node:
+---+ +---+ +---+ +---+
| 1 |--->| 2 |--->| 3 |--->| 4 |---> NULL
+---+ +---+ +---+ +---+
^
|
temp
As an aside, you may also want to add the extra safety of ensuring the node you're given points to NULL, on the off chance the caller may forget to do that. That's as simple as adding this line to the start of the function:
node->pNext = NULL;
Let's make some analogy.
Each node is a station.
NULL is your stop station.
while (temp->pNext != NULL) { temp = temp->pNext; } means drive and visit each station until reach the stop station.
When you reach the stop station, an additional station is needed to be added by temp->pNext = node;
Now the former stop station followed by the new added stop station(implicitly the new NULL) is not a stop station, but the penultimate station to be visited.
have a reference for simple linked list concept
let us take an example
consider
struct node
{
int data;// data which you want to feed.
struct node *next;// gona hold the address of the next data, so that link can be established
}*root,*p; // root is the starting reference to your linked list
case 1: you dont insert any element and your linked list is empty. Now when you insert a new data 10.it will check for any data in the global pointer reference to your linked list, if, the pointer seems to be NULL, then it means your liked list is empty.The memory stack will be created like this.
10
1000
10 is the data, 1000 is its address.
case 2: adding an element at its back.you want to add, data 20 to your linked list.you will be looking whether the linked list is empty or not first, using your global linked list address reference(it will be a pointer variable, holding your linked list 1st address, as per your code)
now when we see root->data is not null 1000->data is 10
we go for root->next which is null, which we come to know that this is the last node. 1000->next is NULL
and we insert the new node address to the root->next so that a link is created to the newly inserted node.
stack will be created like this
10 20
1000 1004
case3: now you want to add another data say 30 to the end of list again. just follow the same as case 2.
check for the node which is currently null, i.e root->next == NULL,
for this you use a loop to find the node which is currently in last, like this.
struct node *temp; // creating a temp node which will be the new node we will insert
temp = (struct node *)malloc(sizeof(struct node));// allocating the size for the temp node, same as the size of previous nodes.
p = root;// i am giving my starting address to pointer p, i traverse the node with pointer p only, since i dont want to loose my root starting address.
while(p->next != NULL)// checking for the last node
p = p->next;// if last node not found, just move to next node, and see whether it is last node or not
p->next = temp;// if last node is found, put the address of newly created temp node to the node previously found last in the linked list.
temp->data = element;// feeding data to the temp node.
temp->next = NULL;// keeping temp node as last, it is necessary to say temp wont has any more node connected.
NOTE dont think this is just a temp node, and will disappear once we come out of function, it is playing with pointer, so it wont destroyed until, the owner wont destroy it.
flow will be
newly created temp address is 1008
1000->next is 1004
1004->next is NULL
so, 1004->next will hold 1008 now
then,1008->data will be 30
then, 1008->next will be NULL
stack will be created like this
10 20 30
1000 1004 1008
I am trying to understand how pointers in linked lists work. So far i am having lots of trouble trying to figure out where the pointer is pointing to and how a pointer of a type struct works( I know we need to allocate memory from the heap but can't quite understand it, but maybe that's a different question altogether).
Lets take this structure:
typedef struct Node {
int data;
struct Node *link;
} Node;
What I think will happen now is:
Say you have a pointer of type Node in the main function, Node* p and this is allocated memory (using malloc).
Now if we have some data p->data=5; , p points to the beginning of this data (at least this is what i think is happening).
Where exactly does link point to?
So now, i come across this particular piece of code:
typedef struct Node {
int data;
struct Node *link;
} Node;
typedef struct List {
Node* head;
int number_of_nodes;
} List;
So this is complete chaos in my brain! .
Now in the structure List, what is head doing? What is it pointing to? And how would you create a linked list at all with these two lists??
I am really trying my level best to understand how linked lists work, but all the pointers make it too hard to keep track of. You might suggest i start with something simple and i did, and i have already mentioned how much i understand. But the head pointer in the second structure has completely thrown me off track!
It would make my life so much more easier if someone could help me explain it while keeping track of the pointers.
Where exactly does link point to?
link points to another object of the same type:
+------+------+ +------+------+ +------+------+
| data | link |---->| data | link |---->| data | link | ----> ...
+------+------+ +------+------+ +------+------+
Now in the structure List, what is head doing? What is it pointing to?
head points to the first node in a list:
+-----------------+ +------+------+ +------+------+
| head |---->| data | link |---->| data | link |----> ...
+-----------------+ +------+------+ +------+------+
| number_of_nodes |
+-----------------+
I am really trying my level best to understand how linked lists work,
Don't feel bad - linked lists threw me for a loop in my Data Structures class (my first "hard" CS class). It took me a solid week longer than my classmates to grok the concept. Hopefully the pictures help.
Edit
what happens if you have a pointer to the structure List, memory allocated and all? Where does it point to then (according to the diagrams, which did help by the way)
So, let's assume you have the following code:
/**
* Create a new list object. head is initially NULL,
* number_of_nodes initially 0.
*/
List *newList( void )
{
List *l = malloc( sizeof *l );
if ( l )
{
l->head = NULL;
l->number_of_nodes = 0;
}
return l;
}
int main( void )
{
List *l = newList();
...
}
Then your picture looks like this:
+---------+ +--------------------+
| l: addr | ----> | head: NULL |
+---------+ +--------------------+
| number_of_nodes: 0 |
+--------------------+
(addr represents some arbitrary memory address)
Now let's say you add a node to your list:
/**
* Create a new node object, using the input data
* link is initially NULL
*/
Node *newNode( int data )
{
Node *n = malloc( sizeof *n );
if ( n )
{
n->data = data;
n->link = NULL;
}
return n;
}
void insertNode( List *l, int data )
{
Node *n = newNode( data );
if ( n )
{
/**
* If list is initially empty, make this new node the head
* of the list. Otherwise, add the new node to the end of the
* list.
*/
if ( !l->head ) // or n->head == NULL
{
l->head = n;
}
else
{
/**
* cur initially points to the first element in the list.
* While the current element has a non-NULL link, follow
* that link.
*/
for ( Node *cur = l->head; cur->link != NULL; cur = cur->link )
; // empty loop body
cur->link = n;
}
l->number_of_nodes++;
}
}
int main( void )
{
List *l = newList();
insertNode( l, 5 );
...
}
Now your picture looks like this:
+---------+ +--------------------+ +------------+
| l: addr | ----> | head: addr | ---> | data: 5 |
+---------+ +--------------------+ +------------+
| number_of_nodes: 1 | | link: NULL |
+--------------------+ +------------+
You could add another node:
int main( void )
{
List *l = newList();
insertNode( l, 5 );
insertNode( l, 3 );
...
}
then your picture becomes
+---------+ +--------------------+ +------------+ +------------+
| l: addr | ----> | head: addr | ---> | data: 5 | +--> | data: 3 |
+---------+ +--------------------+ +------------+ | +------------+
| number_of_nodes: 2 | | link: addr | --+ | link: NULL |
+--------------------+ +------------+ +------------+
Naturally, you'd want to add some error checking and messages in case a node couldn't be allocated (it happens). And you'd probably want an ordered list, where elements are inserted in order (ascending, descending, whatever). But this should give you a flavor of how to build lists.
You'd also need functions to remove items and free that memory. Here's how I'd free an entire list:
void freeList( List *l )
{
Node *prev, *cur = l->head;
while( cur && cur->link )
{
prev = cur;
cur = cur->link;
free( prev );
}
free( cur );
}
int main( void )
{
List *l = newList();
...
freeList( l );
free( l );
...
}
… a pointer of a type struct…
A pointer cannot be of a type struct. A pointer can point to a structure.
C has objects. Objects include char, int, double, structures, and other things. A structure is a collection of objects grouped together.
In main, if you define p with Node *p;, you then have a pointer p. It has no value because you have not given it a value. When you execute p = malloc(sizeof *p);, you request enough memory for the size of the thing p points to (*p). If malloc returns a non-null pointer, then p points to a Node structure.
Then p->data refers to the data member of that structure. p->data is shorthand for (*p).data, in which *p means “the object p points to” and .data means “the data member in that object.”
After p = malloc(sizeof *p); and p->data = 5;, p->link does not point to anything because you have not assigned it a value. In a linked list, you would use malloc to get memory for another Node, and then you would set the p->link in one Node to point to the new Node. In each Node, its link member points to the next Node in the list. Except, in the last Node, p->link is set to a null pointer to indicate it is the last Node.
In List, you would set head to point to the first Node in a list of Node objects.
So today I was watching The mind behind Linux | Linus Torvalds, Linus posted two pieces of code in the video, both of them are used for removing a certain element in a singly-linked list.
The first one (which is the normal one):
void remove_list_entry(linked_list* entry) {
linked_list* prev = NULL;
linked_list* walk = head;
while (walk != entry) {
prev = walk;
walk = walk->next;
}
if (!prev) {
head = entry->next;
} else {
prev->next = entry->next;
}
}
And the better one:
void remove_list_entry(linked_list* entry) {
// The "indirect" pointer points to the
// *address* of the thing we'll update
linked_list** indirect = &head;
// Walk the list, looking for the thing that
// points to the entry we want to remove
while ((*indirect) != entry)
indirect = &(*indirect)->next;
// .. and just remove it
*indirect = entry->next;
}
So I cannot understand the second piece of code, what happens when *indirect = entry->next; evaluates? I cannot see why it leads to the remove of the certain entry. Someone explains it please, thanks!
what happens when *indirect = entry->next; evaluates? I cannot see why it leads to the remove of the certain entry.
I hope you have clear understanding of double pointers1).
Assume following:
Node structure is
typedef struct Node {
int data;
struct Node *next;
} linked_list;
and linked list is having 5 nodes and the entry pointer pointing to second node in the list. The in-memory view would be something like this:
entry -+
head |
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
| |---->| 1 | |---->| 2 | |---->| 3 | |---->| 4 | |---->| 5 |NULL|
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
This statement:
linked_list** indirect = &head;
will make indirect pointer pointing to head.
entry -+
head |
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
| |---->| 1 | |---->| 2 | |---->| 3 | |---->| 4 | |---->| 5 |NULL|
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
^
|
+---+
| |
+---+
indirect
The while loop
while ((*indirect) != entry)
*indirect will give the address of first node because head is pointing to first node and since entry is pointing to second node the loop condition evaluates to true and following code will execute:
indirect = &(*indirect)->next;
this will make the indirect pointer pointing to the next pointer of first node. The in-memory view:
entry -+
head |
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
| |---->| 1 | |---->| 2 | |---->| 3 | |---->| 4 | |---->| 5 |NULL|
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
^
|
+---+
| |
+---+
indirect
now the while loop condition will be evaluated. Because the indirect pointer is now pointing to next of first node, the *indirect will give the address of second node and since entry is pointing to second node the loop condition evaluates to false and the loop exits.
The following code will execute now:
*indirect = entry->next;
The *indirect dereference to next of first node and it is now assigned the next of node which entry pointer is pointing to. The in-memory view:
entry -+
head |
+---+ +-------+ +-------+ +-------+ +-------+ +--------+
| |---->| 1 | |-- | 2 | |---->| 3 | |---->| 4 | |---->| 5 |NULL|
+---+ +-------+ \ +-------+ +-------+ +-------+ +--------+
*indirect \ /
+------------+
Now the next of first node is pointing to third node in the list and that way the second node is removed from the list.
Hope this clear all of your doubts.
EDIT:
David has suggested, in comment, to add some details around - why are the (..) parenthesis required in &(*indirect)->next?
The type of indirect is linked_list **, which means it can hold the address of pointer of type linked_list *.
The *indirect will give the pointer of type linked_list * and ->next will give its next pointer.
But we cannot write *indirect->next because the precedence of operator -> is higher than unary * operator. So, *indirect->next will be interpreted as *(indirect->next) which is syntactically wrong because indirect is a pointer to pointer.
Hence we need () around *indirect.
Also, &(*indirect)->next will be interpreted as &((*indirect)->next), which is the address of the next pointer.
1) If you don't know how double pointer works, check below:
Lets take an example:
#include <stdio.h>
int main() {
int a=1, b=2;
int *p = &a;
int **pp = &p;
printf ("1. p : %p\n", (void*)p);
printf ("1. pp : %p\n", (void*)pp);
printf ("1. *p : %d\n", *p);
printf ("1. *pp : %d\n", **pp);
*pp = &b; // this will change the address to which pointer p pointing to
printf ("2. p : %p\n", (void*)p);
printf ("2. pp : %p\n", (void*)pp);
printf ("2. *p : %d\n", *p);
printf ("2. *pp : %d\n", **pp);
return 0;
}
In the above code, in this statement - *pp = &b;, you can see that without accessing pointer p directly we can change the address it is pointing to using a double pointer pp, which is pointing to pointer p, because dereferencing the double pointer pp will give pointer p.
Its output:
1. p : 0x7ffeedf75a38
1. pp : 0x7ffeedf75a28
1. *p : 1
1. *pp : 1
2. p : 0x7ffeedf75a34 <=========== changed
2. pp : 0x7ffeedf75a28
2. *p : 2
2. *pp : 2
In-memory view would be something like this:
//Below in the picture
//100 represents 0x7ffeedf75a38 address
//200 represents 0x7ffeedf75a34 address
//300 represents 0x7ffeedf75a28 address
int *p = &a
p a
+---+ +---+
|100|---->| 1 |
+---+ +---+
int **pp = &p;
pp p a
+---+ +---+ +---+
|300|---->|100|---->| 1 |
+---+ +---+ +---+
*pp = &b;
pp p b
+---+ +---+ +---+
|300|---->|200|---->| 2 |
+---+ +---+ +---+
^^^^^ ^^^^^
The entry isn't really "deleted", it's just no longer in the list.
If this is your chain:
A --> B --> C --> D --> E --> ■
And you want to delete C, you're really just linking over it. It's still there in memory, but no longer accessible from your data structure.
C
A --> B --------> D --> E --> ■
That last line sets the next pointer of B to D instead of C.
Instead of looping through the entries in the list, as the first example does, the second example loops through the pointers to the entries in the list. That allows the second example to have the simple conclusion with the statement you've asked about, which in English is "set the pointer that used to point to the entry I want to remove from the list so that it now points to whatever that entry was pointing to". In other words, it makes the pointer that was pointing to the entry you're removing point past the entry you're removing.
The first example has to have a special way to handle the unique case of the entry you want to remove being the first entry in the list. Because the second example loops through the pointers (starting with &head), it doesn't have a special case.
*indirect = entry->next;
That just move it to the next node
You need to remove the entry one
So you have to point .. before entry node the next of the entry node
So your loop should stop before the entry
while ((*indirect)->next != entry)
indirect = &(*indirect)->next
(*indirect)->Next =entry-> next
I hope that help you
This example is both a great way of manipulating linked list structures in particular, but also a really excellent way of demonstrating the power of pointers in general.
When you delete an element from a singly-linked list, you have to make the previous node point to the next node, bypassing the node you're deleting. For example, if you're deleting node E, then whatever list pointer it is that used to point to E, you have to make it point to whatever E.next points to.
Now, the problem is that there are two possibilities for "whatever list pointer it is that used to point to E". Much of the time, it's some previous node's next pointer that points to E. But if E happens to be the first node in the list, that means there's no previous node in the list, and it's the top-level list pointer that points to E — in Linus's example, that's the variable head.
So in Linus's first, "normal" example, there's an if statement. If there's a previous node, the code sets prev->next to point to the next node. But if there's no previous node, that means it's deleting the node at the head of the list, so it sets head to point to the next node.
And although that's not the end of the world, it's two separate assignments and an if condition to take care of what we thought of in English as "whatever list pointer it is that used to point to E". And one of the crucial hallmarks of a good programmer is an unerring sense for sniffing out needless redundancy like this and replacing it with something cleaner.
In this case, the key insight is that the two things we might want to update, namely head or prev->next, are both pointers to a list node, or linked_list *. And one of the things that pointers are great at is pointing at a thing we care about, even if that thing might be, depending on circumstances, one of a couple of different things.
Since the thing we care about is a pointer to a linked_list, a pointer to the thing we care about will be a pointer to a pointer to a linked_list, or linked_list **.
And that's exactly what the variable indirect is in Linus's "better" example. It is, literally, a pointer to "whatever list pointer it is that used to point to E" (or, in the actual code, not E, but the passed-in entry being deleted). At first, the indirect pointer points to head, but later, after we've begun walking through the list to find the node to delete, it points at the next pointer of the node (the previous node) that points at the one we're looking at. So, in any case, *indirect (that is, the pointer pointed to by indirect) is the pointer we want to update. And that's precisely what the magic line
*indirect = entry->next;
does in the "better" example.
The other thing to notice (although this probably makes the code even more cryptic at first) is that the indirect variable also takes the place of the walk variable used in the first example. That is, everywhere the first example used walk, the "better" example uses *indirect. But that makes sense: we need to walk over all the nodes in the list, looking for entry. So we need a pointer to step over those nodes — that's what the walk variable did in the first example. But when we find the entry we want to delete, the pointer to that entry will be "whatever list pointer it is that used to point to E" — and it will be the pointer to update. In the first example, we couldn't set walk to prev->next — that would just update the local walk variable, not head or one of the next pointers in the list. But by using the pointer indirect to (indirectly) walk the list, it's always the case that *indirect — that is, the pointer pointed to by indirect — is the original pointer to the node we're looking at (not a copy sitting in walk), meaning it's something we can usefully update by saying *indirect = entry->next.
This will be much easier to understand if you rewrite
indirect = &(*indirect)->next;
As
Indirect = &((*indirect)->next);
The while loop will give us the address of a next pointer belong to some node of which the next pointer is pointing to the entry. So the last statement is actually changing the value of this next pointer so that it doesn’t point to the entry anymore.
And in the special case when the entry is head, the while loop will be skipped and the last line change the value of the head pointer and make it point to the next node of the entry.
Code to my linked list program: This is the code I saved on github
Knowing that pointers always accept the address of a variable. So if someone is writing just the name of array means that that is the address of the first element of the array. Ok that is right that's the address so we need not write an & in front of the array name. But if it were any other thing then we had to use the & sign. So in case of int we write that & sign in front of it. But what in the case of structure that is also a kind of variable of some custom made size?
The code for array may look like this:
int arr[] = {34,234,6234,346,2345,23};
int i;
for(i=0; i<(sizeof(arr)/arr); i++)
int *pointer = arr+i; //Now pointer can point to all the member array one by one
The code for an int may look like this:
int a = 5;
int *pointer = &a;
But if i have two pointers(head & temp) to structure of type struct node. Now I am writing the code for node.
struct node {
int data;
struct node *next; // this is pointer to next element in the Linked List
};
Now initially head is NULL i.e. not pointing to anything
head = NULL;
But on the first insertion to the linked list if do this:
head = temp; // both are pointers
knowing that head can only take the address coz its a pointer but temp is not an array so if write this writing temp doesn't mean its the address of that structure temp
Should I do this
head = &temp
to actually get the address of that temp structure(pointer)?
I get a feeling that we do head = temp and that valid cause like arrays temp is pointer of type structure node. So writing temp means just the address of the temp pointer in the memory. And Now head pointer is having the address of temp & pointing to what head has?
Is head pointing to address of temp or head has now address of temp. Pointing and having are different I guess.
To explain my comment, see the following crude drawings:
In the case of head = temp it will look something like
+------+
| temp | --\
+------+ \ +----------------+
>--> | your structure |
+------+ / +----------------+
| head | --/
+------+
That means that both head and temp points to the same place.
If you on the other hand do head = &temp (and the compiler allowed it), it will look like
+------+ +------+ +----------------+
| head | ---> | temp | ---> | your structure |
+------+ +------+ +----------------+
That is, head points to temp and not to your structure.
head and temp both are of type struct Node*. Assigning temp to head means head is pointing to the same location as that of pointed by temp. &temp is the address of the temp variable which is of pointer to struct NODE type, i.e struct Node**.
temp and &temp both are of different type. You compiler should raise awarning fo the assignment
head = &temp; // assigning incompatible pointer without cast
In case of single variable whether an int or char the address of operator & is used to reference that variable. In case of an array of integers, the name of the array arr[] i.e arr itself represents the address of the first element of the array. See below how the pointer arithmetic operation arrays internally do:
To reference the 'i'th element we write arr[i] = *(arr + i)
So, arr[0] = *(arr + 0) = *(arr)
But in your case, head and temp are pointers of the type struct node*. Using & operator to assign the address of temp to head will firstly won't be allowed by the compiler giving a cast error and moreover it will not serve your purpose either. What you should do is head = temp which will make head and temp point to the struct node.