Originally Posted by
esi
but suppose i want to insert a value between to nodes... how will i tell my pointer to go 1 step back to insert a new node between those two?
For a doubly linked list, you use the "prev" pointer to get the previous node. If the list is singly linked, the general pattern is this:
Code:
node *prev, *curr;
prev = NULL;
curr = list;
if(curr)
{
if(!found(curr))
{
prev = curr;
for(curr = prev->next; curr; curr = curr->next)
{
if(found(curr))
{
break;
}
prev = curr;
}
}
if(curr)
{
/* Found it. At this point, prev points to the previous node, curr to the current node.
* If prev is NULL, the node which was found is at the head of the list, and you may
* have to handle that case specially.
*/
/* Do whatever you need to do here */
}
}
if(!curr)
{
/* Never found it. */
}
In this example, the found() function determines which node to stop at. The if(curr) followed by if(!curr) might seem redundant, but if you try to code it otherwise you will find that you have to duplicate the "never found it" code.