Thursday, September 15, 2016

Free nodes of a linked list in C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
struct node *temp=NULL;

void insert()
{
int lData=0;
struct node *temp1;
printf("Please enter data:\t");
scanf("%d",&lData);
temp=malloc(sizeof(struct node *));
temp1=start;

if(temp1 == NULL )
{
start=temp;
temp->data=lData;
temp->next=NULL;
}
else
{
printf("here1\n");
while(temp1->next != NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
temp->data=lData;
temp->next=NULL;

}
}
void display()
{
struct node *temp1=start;
if(temp1 == NULL )
printf("Linked list is empty\n");
else
{
while(temp1->next != NULL )
{
printf("Final Element is [%d]\n",temp1->data);
temp1=temp1->next;
}
printf("Final Element is [%d]\n",temp1->data);
}
}
/*void free_nodes()
{
struct node *temp1=start;
struct node *temp2;
if(start == NULL )
printf("Linked list is empty\n");
else
{
while(start->next != NULL )
{
temp2=start;
start=start->next;
free(temp2);
}
free(start);
start=NULL;
}
}*/

void free_nodes()
{
struct node *temp1=start;
struct node *temp2;
if(start == NULL )
printf("Linked list is empty\n");
else
{
for(temp2=start;temp2!=NULL;temp2=temp1)
{
temp1=temp2->next;
free(temp2);
}
start=NULL;
}
}
int calculate_length()
{
struct node *temp1=start;
int count=0;
if(temp ==  NULL )
return 0;
else
{
while(temp1->next != NULL )
{
temp1=temp1->next;
count++;
}
count++;
}
return count;
}
int main()
{
int choice;
while(1)
{
printf(" 1. For Insert into link list\n 2. For Free Nodes \n 3. Display link list\n 4. Exit\n\n Enter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
free_nodes();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Invalid choice\n");
break;
}
}
return 0;
}

No comments:

Post a Comment