As I have stated earlier, deletion and insertion of nodes in a linked list is very common feature. In my previous posts, we have seen program on inserting new node in linked list. Today our topic is deletion of first node from a linked list.
How to proceed on this deletion program
Our first job is to create a linked list as usual. In the deletion operation of first node from a linked list, no traversal of pointers is required. In this program, I will use two pointers of structure type. One will point to the first node in the linked list while the other will be made to point to the second node. Then the space associated with the first node is to be disconnected from the linked list first and then deleted.
# include < stdio.h>
# include < stdlib.h>
struct link
{
int data;
struct link *next;
};
int i,x=0;
struct link *start,*p,*node;
void create()
{
char ch;
i=1;
node=start;
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 value for node: %d: ",i);
scanf("%d", &node->data);
node->next = NULL;
printf("\n Input choice n for break: ");
ch = getche();
}
printf("\n Total nodes = %d\n", i);
}
void dis()
{
node=start;
while(node)
{
printf("%d\n",node->data);
node=node->next;
}
}
void del()
{
char c;
printf("\nWant to delete the first node (y/n):-");
c=getche();
if(c=='y')
{
x++;
node=start->next;
free(start);
start=node;
}
else // else block of if(c=='y')
printf("\nYou are not interested in deleting the first node.");
if (x!=0)
{
printf("\n After deleting last node list is as follows\n");
node=start;
while (node)
{
printf(" %d", node->data);
node = node->next;
}
}
}
void main()
{
clrscr();
start = (struct link* ) malloc(sizeof(struct link));
printf("\n Enter value for node: %d: ",i);
scanf("%d", &start->data);
start->next = NULL;
create();
printf("\nPresent position of the linked list before deletion:-\n");
dis();
del();
getch();
}
Technical analysis of this deletion program on linked list
List pointer of the linked list is declared as external variable. After creating the linked list we call the ‘void del ()’ function to delete the first node of the linked list. This del () function performs a very simple job here. It assigns the address of second node of the linked list on a moving pointer ‘node’ and frees the location of the linked list pointer by
list pointer. Then it again assigns the second location address on the list pointer ‘start’.
No comments:
Post a Comment