Monday, September 12, 2016

Linked list Delete Middle Element Code

#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(temp == 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);
}
}
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;
}
void delete_middle()
{
struct node *temp1=start;
int count =1;
int length=0;
int middle=-1;
length=calculate_length();
if(length%2 == 0 )
{
middle=length/2;
}
else
{
middle=(length/2)+1;
}
while(1)
{
printf("count [%d] middle [%d]\n",count,middle);
if(count == middle - 1)
{
struct node *del=temp->next;
temp1->next=temp1->next->next;
free(del);
break;
}
else
temp1=temp1->next;
count++;
}
}
int main()
{
int choice;
while(1)
{
printf(" 1. For Insert into link list\n 2. For Delete Middle\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:
delete_middle();
printf("delete middle\n");
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("Invalid choice\n");
break;
}
}
return 0;
}

No comments:

Post a Comment