Doubly Linked list

Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.

PROGRAM:

//Code by Vikas
#include <stdio.h>
#include<stdlib.h>
void create();
void insert(int n);
void delete();
void display();

typedef struct node
{
    int data;
    struct node *llink,*rlink;
}snode;

struct node *head,*tail;
void create()
{
    head=tail=NULL;
 
}
void insert(int n)
{
    snode *newnode;
    newnode=(snode*)malloc(sizeof(snode));
    newnode->data=n;
    newnode->llink=NULL;
    newnode->rlink=NULL;
    if(head==NULL)
    {
        head = newnode;
        tail=newnode;
     
    }
    else
    {
        tail->rlink=newnode;
        newnode->llink=tail;
        tail=newnode;
    }
}
void delete()
{
    snode *temp;
    if(head==NULL)
    printf("\n No double linked list created so far");
    else
    {
     if(head==tail)
     {
        free(head);
        free(tail);
        head=tail=NULL;
     
     }
     else
     {
     temp=head;
     head=head->rlink;
     head->llink=NULL;
     free(temp);
     }
    }
}
void display()
{
    snode *temp;
    if(head==NULL)
    printf("\nNo  linked list");
    else
    {
        printf("\n left to right traversing");
        for(temp=head;temp!=NULL;temp=temp->rlink)
        {
            printf("%d\t",temp->data);
        }
        printf("\n right to left traversing");
        for(temp=tail;temp!=NULL;temp=temp->llink)
        {
            printf("%d\t",temp->data);
        }
    }
}
void main()
{
    int op,n;
    while(1)
    {
        printf("\n1:Create\n2:Insert\n3:Delete\n4:Display\n5:Exit");
        printf("\n Enter an option");
        scanf("%d",&op);
        switch(op)
        {
            case 1:create();
            break;
            case 2:printf("\n Enter an element");
            scanf("%d",&n);
            insert(n);
            break;
            case 3:
            delete();
            break;
            case 4:display();
            break;
            case 5:exit(0);
        }
    }


Recommended: solve it on “PRACTICE ” first, before moving on to the solution.


Previous Post Next Post