In data Structure using C Programming Language, for deletion of any node from linked list , you have to take the location which node is to be deleted and then traverse through the linked list to reach that node with the help of two moving pointers. In our program one is ‘start’ and the other pointer is ‘p’. One moving pointer of the linked list should be kept one node ahead of the other moving pointer. In this program, pointer ‘start’ is ahead of ‘p’. When ‘start’ reaches the specific node to be deleted from the linked list, necessary connection of address pointers of the node pointed by ‘p’ and the node next to ‘start’ are to be connected.
In our previous post we have program on deletion of first and last node from a linked list. Here are the codes for the program on deleting any location node from a linked list.
# include < stdio.h>
# include < stdlib.h>
struct link
{
char info[20];
struct link *next;
};
int i;
int number ;
struct link *start=NULL,*p,*node;
void create()
{
char ch;
i=1;
node=start;
node->next = (struct link* ) malloc(sizeof(struct link));
node = node->next;
printf("\n Enter string for node: %d: ",i);
scanf("%s", node->info);
fflush(stdin);
node->next = NULL;
printf("\n Enter choice--'n' for break: ");
ch = getche();
while(ch != 'n')
{
i=i+1;
node->next = (struct link* ) malloc(sizeof(struct link));
node = node->next;
printf("\n Enter string for node: %d: ",i);
scanf("%s", node->info);
node->next = NULL;
printf("\n Enter choice-- 'n' for break: ");
ch = getche();
}
printf("\n Total nodes = %d\n", i);
}
void dis(struct link *n)
{
node=n->next;
while(node)
{
printf("\n 0x%x ", node);
printf("%s\n",node->info);
node=node->next;
}
}
void del(struct link *n)
{
int num=0;
int number = 1;
int del_node;
node=n->next;
p = n;
printf("\n Input node number you want to delete:");
scanf(" %d", &del_node);
while(node)
{
if(number == del_node)
{
p->next = node->next;
free(node);
num++;
break ;
}
else
{
node = node->next;
p = p->next;
number ++;
}
}
if(num!=0)
{
printf("\n Desired node is deleted.\n");
dis(start);
}
else
printf("Deletion not possible.");
}
void main()
{
clrscr();
create();
dis(start);
del(start);
getch();
}
No comments:
Post a Comment