Singular Linked List


//Singular Linked List

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
 int data;
 struct node *link;
};
struct node *first=NULL,*last=NULL,*next,*prev,*cur;

void create()
{
 int i;
 cur=(struct node*)malloc(sizeof(struct node));
 printf("Enter Data: ");
 scanf("%d",&cur->data);
 cur->link=NULL;
 first=cur;
 last=cur;
}

void insert()
{
 int pos,c=1;
 cur=(struct node*)malloc(sizeof(struct node));
 printf("\nEnter the Data: ");
 scanf("%d",&cur->data);
 printf("\nEnter the Data Position: ");
 scanf("%d",&pos);
 if((pos==1)&&(first!=NULL))
 {
  cur->link=first;
  first=cur;
 }
 else
 {
  next=first;
  while(c<pos)
  {
   prev=next;
   next=prev->link;
   c++;
  }
  if(prev==NULL)
  {
   printf("\nInvalid Position");
  }
  else
  {
   cur->link=prev->link;
   prev->link=cur;
  }
 }
}

void del()
{
 int pos,c=1;
 printf("Enter the position: ");
 scanf("%d",&pos);
 if(first==NULL)
 {
  printf("\nList is Empty");
 }
 else if(pos==1 && first->link==NULL)
 {
  printf("Deleted element is %d\n",first->data);
  free(first);
  first=NULL;
 }
 else if(pos==1 && first->link!=NULL)
 {
  cur=first;
  first=first->link;
  cur->link=NULL;
  printf("\nDeleted Element is %d\n",cur->data);
  free(cur);
 }
 else
 {
  next=first;
  while(c<pos)
  {
   cur=next;
   next=next->link;
   c++;
  }
  cur->link=next->link;
  next->link=NULL;
  if(next==NULL)
  {
   printf("\nInvalid position ");
  }
  else
  {
   printf("\nDeleted element is %d\n",next->data);
   free(next);
  }
 }
}
void display()
{
 cur=first;
 if(cur==NULL)
 {
  return;
 }
 while(cur!=NULL)
 {
  printf("\n%d",cur->data);
  cur=cur->link;
 }
}
void main()
{
 int ch;
 clrscr();
 printf("\n\nSingly Linked List");
 do
 {
  printf("\n\n1.Create\n2.Insert\n3.Delete\n4.Display\n5.Exit");
  printf("\nEnter your choice: ");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:
create();
break;
   case 2:
insert();
break;
   case 3:
del();
break;
   case 4:
display();
break;
   case 5:
exit(0);
   default:
printf("Invalid Choice...");
   }
  }
  while(1);
}


Post a Comment

Previous Post Next Post