Wednesday, August 31, 2011

Write a code to create Double Linked List.


//Write a code to create Double Linked List.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
main()
{
struct node *start=NULL,*end=NULL;
int n;
void create(struct node **,struct node **,int);
void show(struct node *,struct node *);
void insert_before(struct node **start);
struct node* search_bitem(struct node *start,int item);
printf("Enter the number of elements you want in your linked list :");
scanf("%d",&n);
create(&start,&end,n);
show(start,end);
insert_before(&start);
show(start,end);
getch();  
}

void create(struct node **start,struct node **end,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
 p=(struct node *)malloc(sizeof(struct node));
 printf("Enter the %d element :",i);
 scanf("%d",&(p->data));
 p->next=NULL;
 p->prev=NULL;
 if(*start==NULL)
    *start=p;
 else
   {
    lst->next=p;
    p->prev=lst;
   }
  lst=p;
 }
  *end=lst;
}

void show(struct node *start,struct node *end)
{
     struct node *t;
     t=start;
printf("Forwared traversing :\n");
while(t!=NULL)
{
printf(" %d\n",t->data);
t=t->next;
}

t=end;
printf("\nBackward traversing :\n");
while(t!=NULL)
{
printf(" %d\n",t->data);
t=t->prev;
}
}

void insert_before(struct node **q)
{
 struct node *p,*loc;
 int item;
 printf("Enter the item before which new element is to be inserted ");
 scanf("%d",&item);
 if(*q==NULL)
 {
  printf("\nItem before which element is to be inserted is not in the list");
  return;
 }

    p=(struct node *)malloc(sizeof(struct node));
    printf("Enter the element to be inserted ");
    scanf("%d",&(p->data));
    p->next=NULL;
    p->prev=NULL;
 
 if(item==(*q)->data)
 {
      (*q)->prev=p;
      p->next=*q;
      *q=p;
 }
 else
 {
 loc=(struct node *)search_bitem(*q,item);
  if(loc==NULL)
    printf("\nItem before which element is to be inserted is not in the list");
  else
  {
      p->next=loc->next;
      p->prev=loc;
      (loc->next)->prev=p;
      loc->next=p;
  }
 }
}

struct node* search_bitem(struct node *start,int item)
{
       struct node *prev,*ptr;
       ptr=start;
        prev=ptr;
        ptr=ptr->next;
        while(ptr!=NULL)
        {
          if(item==(ptr->data))
           return prev;
          prev=ptr;
          ptr=ptr->next;
        }
        return NULL;
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More