This is my full code:
Code:
#include <stdio.h>
#include <malloc.h>
typedef struct visit_node
{
char v_name;
struct visit_node *next_ptr;
}
visit_node_type, *visit_ptr_node_type;
visit_ptr_node_type anchor;
void insert_after(visit_ptr_node_type after_this_node, visit_ptr_node_type new_node)
{
if(anchor==NULL)
{
new_node->next_ptr=NULL;
anchor=new_node;
}
else
{
new_node->next_ptr=after_this_node->next_ptr;
after_this_node->next_ptr=new_node;
}
}
void delete(visit_ptr_node_type this_is_the_node)
{
visit_ptr_node_type one_back;
if(anchor == NULL)
printf("\n The list is empty");
else
{
if(this_is_the_node==anchor)
anchor=anchor->next_ptr;
else
{
one_back=anchor;
while(one_back->next_ptr != this_is_the_node)
one_back=one_back->next_ptr;
one_back->next_ptr = (this_is_the_node) ->next_ptr;
}
free(this_is_the_node);
}
}
main()
{
visit_ptr_node_type p1,p2;
visit_ptr_node_type hadash;
anchor=(visit_ptr_node_type)malloc(sizeof(visit_node_type));
p1=(visit_ptr_node_type)malloc(sizeof(visit_node_type));
p2=(visit_ptr_node_type)malloc(sizeof(visit_node_type));
anchor->v_name ='A';
p1->v_name='I';
p2->v_name='Y';
anchor->next_ptr=p1;
p1->next_ptr=p2;
p2->next_ptr=NULL;
// clrscr();
printf("\n FIRST LIST");
printf("\n The characters in the list are :");
printf("\n first= %c second= %c third= %c\n",anchor->v_name,
anchor->next_ptr->v_name,anchor->next_ptr->next_ptr->v_name);
hadash=malloc(sizeof(visit_node_type));
hadash->v_name='N';
printf("\n Insert the char N after the char I");
insert_after(p1,hadash);
printf("\n The characters in the list are :");
printf("\n first= %c second= %c third= %c fourth= %c\n",anchor->v_name,
anchor->next_ptr->v_name,anchor->next_ptr->next_ptr->v_name,
anchor->next_ptr->next_ptr->next_ptr->v_name);
printf("\n Delete the char I from the list");
delete(p1);
printf("\n The characters in the list are :");
printf("\n first= %c second= %c third= %c\n",anchor->v_name,
anchor->next_ptr->v_name,anchor->next_ptr->next_ptr->v_name);
printf("\n Delete the first char A {anchor} from the list");
delete(anchor);
printf("\n The characters in the list are :");
printf("\n first= %c second= %c third= %c\n",anchor->v_name,
anchor->next_ptr->v_name,anchor->next_ptr->next_ptr->v_name);
printf("\n THE SECOND LIST IS EMPTY");
anchor=NULL;
printf("\n Delete one char from the empty list");
delete(anchor);
printf("\n \n Insert the char N into the empty list:");
insert_after(anchor,hadash);
printf("\n The characters in the list are : first= %c",anchor->v_name);
}
If I send anchor to function as a pointer (&anchor), then also the nodes in the middle don't get deleted (p1).
Ronen