Insert an element at first position in a given DLL  
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *prev;
    struct node *next;
};
struct node *start=NULL;
main()
{
    int i,value,ne;  // ne=Number of element in list
    struct node *n,*temp;
    n=malloc(sizeof(struct node));
    
    printf("\n\n\tHow many value do you want to Enter in List: ");
    scanf("%d",&ne);
    printf("\nEnter first data for list: "); // create DLL
    scanf("%d",&value);
    n->data=value;
    n->prev=NULL;
    n->next=NULL;
    start=n;
    for(i=2;i<=ne;i++)
    {
        n=malloc(sizeof(struct node));
        printf("Enter next data: ");
        scanf("%d",&value);
        n->data=value;
        n->prev=NULL;
        n->next=NULL;
        temp=start;
        while(temp->next!=NULL)
            temp=temp->next;
        temp->next=n;
        n->prev=temp;
    }
    //for display
    if(start==NULL)
        printf("\n\t** List is empty **");
    else
    {
        temp=start;
        printf("\n\tData in the List: ");
        while(temp!=NULL)
        {
            printf("%d\t",temp->data);
            temp=temp->next;
        }
    }
    //Insertion at first position
    n=malloc(sizeof(struct node));
    printf("\n\n\tEnter a Value for insert at first position: ");
    scanf("%d",&value);
    n->data=value;
    n->prev=NULL;
    n->next=NULL;
    n->next=start;
    start->prev=n;
    start=n;
    //for display updated List
    if(start==NULL)
        printf("\n\t** List is empty **");
    else
    {
        temp=start;
        printf("\n\t\t** Data inserted successfully at first position **");
        printf("\n\n\t Updated List: ");
        while(temp!=NULL)
        {
            printf("%d\t",temp->data);
            temp=temp->next;
        }
    }
    getch();
}
OUTPUT:
 
1 Comments
👍🏼👍🏼👍🏼👍🏼👍🏼
ReplyDeletePlease do not enter any spam link in the comment box.