Doubly LinkedList Deletion at any Position

Algorithm

INPUT: HEADER IS POINTER TO THE HEADER NODE OF THE LINKEDLIST AND POSITION
OUTPUT: LINKEDLIST WITHOUT THE DELETED 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: ENDWHILE
STEP 7: PTR2=PTR->RLINK
STEP 8: PTR1->RLINK=PTR
STEP 9: PTR2->LLINK=PTR1
STEP 10: FREE(PTR)
STEP 11: ENDWHILE

Code

#include <stdio.h>
#include <stdlib.h>
int getnode(int);
void display();
void displayrev();
void deleteatany();
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 POSITION WHERE YOU WANT TO DELETE");
    scanf("%d",&pos);
    deleteatany();
    printf("\n");
    display(header);
    return 0;
}

void deleteatany()
{
    ptr = header->rlink;
    struct node *ptr1;
    ptr1 = malloc(sizeof(struct node));
    for (int i = 1; i < pos; i++)
    {
        ptr1 = ptr;
        ptr = ptr->rlink;
    }
    ptr2 = ptr->rlink;
    ptr1->rlink = ptr2;
    ptr2->llink = ptr1;
    free(ptr);
}
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 POSITION WHERE YOU WANT TO DELETE3
1 2 4 5

Leave a Comment

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