Sunday 25 March 2012

program in c to delete the element from linked list of last position element


W.A.P to delete the element from linked list of last position element.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define NULL 0
struct node
{
int data;
struct node *link;
}*start,*temp,*pre;
void display();
void main()
{
int i,q,x;
char ch;
clrscr();
start=NULL;
for(i=0;i<=1;i++)
{
if(start==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
printf("\nEnter value for node: -");
scanf("%d",&temp->data);
start=temp;
temp->link=NULL;
}
else
{
while(1)
{
printf("\nDo you want create one more node(Y/N):- ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y' || ch=='Y')
{
temp->link=(struct node *)malloc(sizeof(struct node));
temp=temp->link;
printf("\nEnter value for node: -");
scanf("%d",&temp->data);
}
else
{
temp->link=NULL;
break;
}
}
}
}
printf("\n\n\nThe value of nodes are before delete :\n");
display();
//For delete last node
temp=start;
while(temp->link!=NULL)
{
pre=temp;
temp=temp->link;
}
pre->link=NULL;
free(temp);
printf("\n\nAfter deleting  last node the new nodes are :\n");
display();
getch();
}
void display()
{
temp=start;
while(temp!=NULL)
{
printf("%4d",temp->data);
temp=temp->link;
}
}
output:

Enter value for node: -45
Do you want create one more node(Y/N):- y
Enter value for node: -12
Do you want create one more node(Y/N):- y
Enter value for node: -10
Do you want create one more node(Y/N):- y
Enter value for node: -85
Do you want create one more node(Y/N):- n
The value of nodes are before delete :
  45  12  10  85
After deleting  last node the new nodes are :
  45  12  10

No comments:

Post a Comment