Wednesday, 11 September 2013

What more does the code need to delete a node from a linked list successfully?

What more does the code need to delete a node from a linked list
successfully?

I want to delete a given node from a linked list by the node's index
number (serial number). So what I tried to do in my function is that,
first I have taken the user input of the index number. Then I used two
node type pointers temp and current. I started traversing the list with
current and when the index number of the node matches with the user input,
I tried to delete the node. So far it is correct. I am facing problem with
the deletion logic. Here is the code I tried:
void delete_node(struct node **start,int index_no)
{
int counter=0;
struct node *temp, *current;
temp=(struct node *)malloc(sizeof(struct node));
current=(struct node *)malloc(sizeof(struct node));
current=*start;
while(current->next!=NULL)
{
counter++;
if(counter==index_no)
{
temp= current->next;
free(current);
/*I guess some code is missing here. Help me finding the logic.*/
}
else
{
printf("\n The index number is invalid!!");
}
}
}
The commented portion lacks the deletion logic. Also, I have a feeling
that this code is not space and time-efficient. If it is so, please
suggest to a way to make it more compact.

No comments:

Post a Comment