pointers are awesome! very usefull for getting rid of exceptional situations.
example.
say you have three nodes in a list.
1 2 3 4
|
struct Node{
int data;
Node * next;
};
|
1 2 3 4 5 6
|
Node n1, n2, n3;
//data doesn't matter
n1.next = &n2;
n2.next = &n3;
n3.next = NULL;
Node * head = &n1;
|
now lets say you want to iterate over them and erase the n2 node.
for that you need to make n1 point to n3.
you have three choices.
1) use two runners to always remember who the previous node is to erase it
2) use a pointer to a pointer to a node
3) add a Node * prev; to the Node struct
in the first case you have issues if the node you want to erase is the first one, which is at least one additional if to the loop which runs on the code, unless you want to use a dummy Node or some other trick which poses other issues under curtain circumstances.
in the third case your wasting memory you don't have to waste.
the second case has the "cleanest" code by me.
1 2 3 4 5 6 7 8 9
|
Node ** runner = &head;
while( *runner != NULL ){
if( (*runner)->data == BAD_DATA ){
*runner = (*runner)->next;
//delete old node if you want
continue;
}
runner = &(*runner)->next;
}
|
notice that this code would work if you would need to erase the first node or the last, you don't need any additional ifs for exceptional situations, no need to maintain prev pointers, or dummy nodes or any thing like that, however i'm not sure efficiency wise is the best way to iterate over a list while deleting stuff from it.