Hello friend,
                                        here i am write this article for doubly linked list.So i hope you like this.


doubly linked list in c

  • Doubly linked list


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

struct node* createnode()
{
 int x;
 temp=(struct node*)malloc(sizeof(struct node));
 printf("\nEnter value:");
 scanf("%d",&x);
 if(temp!=NULL)
 {
  temp->data=x;
  temp->next=NULL;
  temp->prev=NULL;
  return temp;
 }
 else
 {
  printf("\nMemory not allocated");
  return 0;
 }
}

void display()
{
 if(first!=NULL)
 {
  for(temp=first;temp->next!=NULL;temp=temp->next)
  printf("%d->",temp->data);
  printf("%d->NULL",temp->data);
 }
 else
  printf("\nLinked list is empty");
}
void insf()
{
 newnode=createnode();
 if(newnode==NULL)
  printf("\nMemory not allocated.");
 else
 {
  if(first==NULL)
   first=last=newnode;
  else
  {
   newnode->next=first;
   first->prev=newnode;
   first=newnode;
  }
 }
 display();
}

void insl()
{
 newnode=createnode();
 if(first==NULL)
 {
  first=last=newnode;
 }
 else
 {
  last->next=newnode;
  newnode->prev=last;
  last=newnode;
 }
 display();
}

int countnode()
{
 int i=0;
 for(temp=first;temp->next!=NULL;temp=temp->next,i++);
 i++;
 return i;
}


void delf()
{
 if(first==NULL)
  printf("\nUnderflow");
 else if(first==last)
 {
  free(first);
  first=NULL;
 }
 else
  {
   temp=first;
   first->next->prev=NULL;
   first=temp->next;
   free(temp);
  }
 display();
}



void delbsp()
{
 int pos,i=1;
 printf("\nEnter position");
 scanf("%d",&pos);
 if(pos>countnode())
 {
  printf("\nEnter valid position\n");
 }
 else
 {
  if(pos==1)
   printf("\nEnter valid number");
  else if(pos==2)
  {
   temp=first;
   first=temp->next;
   first->prev=NULL;
   free(temp);
  }
  else
  {
   for(temp=first;i<pos-1;i++,temp=temp->next);
   temp->prev->next=temp->next;
   temp->next->prev=temp->prev;
   free(temp);
  } 
 }
 display();
}

void dell()
{
 if(first==NULL)
  printf("\nunderflow");
 else if(first==last)
 {
  free(first);
  first=NULL;
 }
 else
 {
  last->prev->next=NULL;
  temp=last;
  last=last->prev;
  free(temp);
 }
 display();
}

main()
{
 int choice;
 while(1)
 {
  printf("\nMENU\n1.insert at first\n2.insert at last\n3.delete at first\n4.delete before specific position\n5.delete last\n6.display linked list\n7.EXIT\n");
  printf("\nENTER CHOICE:");
  scanf("%d",&choice);
  switch(choice)
  {
   case 1:
    insf();
    break;
   case 2:
    insl();
    break;
   case 3:
    delf();
    break;
   case 4:
    delbsp();
    break;
   case 5:
    dell();
    break;  
   case 6:
    display();
    break;
   case 7:
    exit(0);
   default :
    printf("\nenter valid choice");
  }
 }
}

Happy coding💚

Post a Comment

Hii

أحدث أقدم