Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




PROGRAM TO SEARCH IN DOUBLY LINKED LIST

Download Attachment
/******************************************/
/* PROGRAM TO SEARCH IN DOUBLY LINKED LIST*/
/******************************************/

#include < stdio.h>
#include < conio.h>
#include < malloc.h>
#include < process.h>
#include < ctype.h>

struct doubly_list
{
    int info;
    struct doubly_list *prev;
    struct doubly_list *next;
}*first,*last,*newnode,*ptr;

void main()
{
    int item,i,loc;
    char ch;
    clrscr();
    newnode=(struct doubly_list*)malloc(sizeof(struct doubly_list));
    first=newnode;
    last=newnode;
    newnode->prev=NULL;
    do
    {
        printf("\nEnter data: ");
        scanf("%d",&item);
        newnode->info=item;
        printf("\nDo you want to create another node:(y/n)");
        fflush(stdin);
        scanf("%c",&ch);
        if(tolower(ch)=='y')
        {
            newnode->next=(struct doubly_list*)malloc(sizeof(struct doubly_list));
            newnode->next->prev=newnode;
            newnode=newnode->next;
            last=newnode;
        }
        else
        {
            newnode->next=NULL;
        }
    }while(tolower(ch)!='n');
    printf(“\nDoubly Linked List is:”);
    ptr=first;
    i=1;
    while(ptr!=NULL)
    {
        printf("\nNode %d : %d",i,ptr->info);
        ptr=ptr->next;
        i++;
    }

    printf("Enter the item tobe searched: ");
    scanf("%d",&item);
    loc=0;
    fflush(stdin);
    printf("\nDo you want to search from start(y/n): ");
    scanf("%c",&ch);
    if(tolower(ch)=='y')
    {
        i=1;
        ptr=first;
        while(ptr!=NULL)
        {
            if((ptr->info)==item)
            {
                loc=i;
                break;
            }
            ptr=ptr->next;
            i++;
        }
        if(loc==0)
        {
            printf("\n%d is not present in the linked list",item);
        }
        else
        {
printf("\n%d is present in the linked list at %d location",item,loc);
        }
    }
    else
    {
        i=i-1;
ptr=last;
        while(ptr!=NULL)
        {
            if((ptr->info)==item)
            {
                loc=i;
                break;
            }
            ptr=ptr->prev;
            i--;
        }
if(loc==0)
        {
            printf("\n%d is not present in the linked list",item);
        }
        else
        {
printf("\n%d is present in the linked list at %d location",item,loc);
        }
    }    
    getch();
}
Share this article   |    Print    |    Article read by 3102 times
Author:
Rohit kakria
I am software developer
Related Articles:
Related Interview Questions: No related interview question