45) Write a C program to create a singly linked list,display it and erase complete list.


#include<stdio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
NODE *create();
void display(NODE *);
NODE *findlast(NODE *);
NODE *erase(NODE *);
void main()
{
NODE *list=NULL;
clrscr();
printf(“\nCreate list.”);
list=create();
printf(“\n\nList is: “);
display(list);
list=erase(list);
printf(“\n\nList after erasing: “);
display(list);
getch();
}
NODE *getnode()
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
printf(“\nEnter the data: “);
scanf(“%d”,&temp->data);
temp->next=NULL;
return temp;
}
NODE *create()
{
NODE *ptr,*temp,*list=NULL,*prev;
int n,i;
printf(“\n Enter how many nodes : “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
temp=getnode();
if(list==NULL)
list=temp;
else
{
ptr=findlast(list);
ptr->next=temp;
}
}
return(list);
}
void display(NODE *list)
{
NODE *ptr;
for(ptr=list;ptr!=NULL;ptr=ptr->next)
printf(“%d->”,ptr->data);
printf(“NULL”);
}
NODE *findlast(NODE *list)
{
NODE *ptr;
for(ptr=list;ptr->next!=NULL;ptr=ptr->next);
return(ptr);
}
NODE *erase(NODE *list)
{
NODE *ptr,*prev;
for(ptr=list,prev=list;ptr!=NULL;prev=ptr,ptr=ptr->next)
free(prev);
list=NULL;
return(list);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s