Implement insertion, Deletion and Display of node in the beginning and at the end of Singly Linked List / Data Structure /Linear Data Structure

                Problem: Singly Linked List


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

struct node
{
int data;
struct node *link;
}*head=NULL,*temp,*new1,*new2,*new3,*new4;

void insbeg();
void inspos();
void insend();
int len();
void display();
void del();

void main()
{
int n,i;
clrscr();
while(1)
{
printf("\n***** LINKED LIST OPERATIONS *****");
printf("\n1.INSERT\n2.DELETE\n3.DiSPLAY\n4.EXIT");
printf("\nENTER YOUR CHOICE: ");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\n***INSERT OPERATIONS***");
printf("\n1.INSERT FROM BEGINNING\n2.INSERT FROM POSITION\n3.INSERT FROM END");
printf("\nENTER YOUR CHOICE:");
scanf("%d",&i);
switch(i)
{
case 1:
insbeg();
break;
case 2:
inspos();
break;
case 3:
insend();
break;
default:
printf("WRONG CHOICE!!");
break;
}
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("WRONG CHOICE!!!");
}
}
}

int len()
{
int count=0;
temp=head;
while(temp!=NULL)
{
count++;
temp=temp->link;
}
return count;
}

void insbeg()
{
int n;
 new1=(struct node*)malloc(sizeof(struct node));
 printf("Enter the data:");
 scanf("%d",&n);
 new1->data=n;
 new1->link = NULL;
 if(head==NULL)
 {
 head=new1;
 }
 else
 {
 new1->link=head;
 head=new1;
 }
}

void insend()
{
int n;
 new2=(struct node*)malloc(sizeof(struct node));
 printf("Enter the data:");
 scanf("%d",&n);
 new2->data=n;
 new2->link = NULL;
  if(head==NULL)
  {
  head = new2;
  }
  else
  {
  temp=head;
    while(temp->link!=NULL)
    {
    temp=temp->link;
    }
    temp->link=new2;
  }
}

void inspos()
{
int loc,length,i=1,n;
printf("ENTER LOCATION:");
scanf("%d",&loc);

length=len();
if(loc==length+1)
{
insend();
}
else if(loc>length && loc!=0 && loc!=1)
{
printf("\n INVALID LOCATION");
printf("\n Currently list is having %d nodes",length);
}
else if(loc==0)
{
printf("\n INVALID LOCATION");
}
else
{
temp=head;
while(i<loc-1)
{
temp=temp->link;
i++;
}
new3=(struct node*)malloc(sizeof(struct node));
printf("\nENTER THE DATA:");
scanf("%d",&n);
new3->data=n;
new3->link=temp->link;
temp->link=new3;
}
}

void del()
{
int loc,l,i=1;
l=len();
if(l==0)
{
printf("\n There are very less element to delete!!");
printf("\n Currently list is having %d nodes",l);
}
else
{
printf("\nENTER THE LOCATION:");
scanf("%d",&loc);

if(loc>l)
{
printf("\nINVALID LOCATION!!");
printf("\nCurrently list is having %d nodes",l);
}
else if(loc==1)
{
temp=head;
head=temp->link;
printf("%d is a deleted node",temp->data);
temp->link=NULL;
free(temp);
}
else
{
temp=head;
while(i<loc)
{
temp=temp->link;
i++;
}
new4=temp->link;
temp->link=new4->link;
printf("%d is a deleted node",temp->data);
new4->link=NULL;
free(new4);
}
}
}
void display()
{
temp=head;
if(temp==NULL)
{
printf("LINKED LIST IS EMPTY!!");
}
else
{
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->link;
}
}
}

 

Comments