Doubly LinkedList Insertion at any Position

Algorithm

INPUT: HEADER IS POINTER TO THE HEADER NODE OF THE LINKEDLIST
OUTPUT: LINKEDLIST WITH THE INSERTED ELEMENT
DATA STRUCTURE: DOUBLY LINKEDLIST

STEP 1: START
STEP 2: PTR=HEADER->LINK
STEP 3: FOR( I =1 TO POS ) DO
STEP 4: PTR1=PTR
STEP 5: PTR=PTR->RLINK
STEP 6: NEW=NEWNODE(NODE)
STEP 7: NEW->DATA=ITEM
STEP 8: NEW->RLINK=PTR
STEP 9: NEW->LLINK=PTR1
STEP 10: PTR1->RLINK=NEW
STEP 11: PTR->LLINK=NEW
STEP 12: END

Code

#include <stdio.h>
#include <stdlib.h>
int getnode(int);
void display();
void displayrev();
void insertatany();
int x, pos, n, item;
struct node
{
    int data;
    struct node *llink;
    struct node *rlink;
};
struct node *prev, *head, *tail, *news, *p, *ptr, *ptr1, *ptr2;
struct node *q1;
struct node *header, *header1;
struct node *q, *r, *s;
int main()
{
    int a;
    char ch;
    printf("ENTER THE LIMIT ");
    scanf("%d", &n);
    getnode(n);
    printf("ENTER THE DATA YOU WANT TO INSERT:");
    scanf("%d", &item);
    printf("Enter the position where you want to insert");
    scanf("%d",&pos);
    insertatany();
    display(header);
    return 0;
}

void insertatany()
{
    ptr = header->rlink;
    for (int i = 1; i < pos; i++)
    {
        ptr1 = ptr;
        ptr = ptr->rlink;
    }
    news = malloc(sizeof(struct node));
    news->data = item;
    news->rlink = ptr;
    news->llink = ptr1;
    ptr1->rlink = news;
    ptr->llink = news;
}
void display(struct node *head1)
{
    struct node *ptr;
    ptr = head1->rlink;
    while (ptr != NULL)
    {
        printf("%d ", ptr->data);
        ptr = ptr->rlink;
    }
}
void displayrev()
{
    struct node *ptr;
    ptr = tail;
    printf("reverse traversal ");
    while (ptr != NULL)
    {
        printf("%d ", ptr->data);
        ptr = ptr->llink;
    }
}
int getnode(int n)
{
    header = malloc(sizeof(struct node));
    head = NULL;
    ptr = malloc(sizeof(struct node));
    for (int i = 0; i < n; i++)
    {
        ptr->llink = NULL;
        p = malloc(sizeof(struct node));
        scanf("%d", &p->data);
        ptr->rlink = p;
        p->llink = ptr;
        p->rlink = NULL;
        if (head == NULL)
        {
            head = p;
            p->llink = NULL;
            ptr->llink = head;
        }
        else
        {
            prev->rlink = p;
            p->llink = prev;
        }
        prev = p;
    }
    tail = prev;
    header->rlink = head;
    header->llink = NULL;
    display(header);
    displayrev();
    return 0;
}

Output

user@computer$ : ENTER THE LIMIT 5
1
2
3
4
5
1 2 3 4 5
reverse traversal
5 4 3 2 1
ENTER THE DATA YOU WANT TO INSERT:6
Enter the position where you want to insert
2 1 6 2 3 4 5

Leave a Comment

Your email address will not be published. Required fields are marked *