Untitled

 avatar
unknown
plain_text
2 months ago
2.7 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
    struct node *prev;
};
struct node *head = NULL;
void createlist()
{
    struct node *n1, *n2, *n3, *n4, *n5, *n6, *n7;
    n1 = (struct node *)malloc(sizeof(struct node));
    n2 = (struct node *)malloc(sizeof(struct node));
    n3 = (struct node *)malloc(sizeof(struct node));
    n4 = (struct node *)malloc(sizeof(struct node));
    n5 = (struct node *)malloc(sizeof(struct node));
    n6 = (struct node *)malloc(sizeof(struct node));
    n7 = (struct node *)malloc(sizeof(struct node));
    n1->data = 10;
    n2->data = 20;
    n3->data = 30;
    n4->data = 40;
    n5->data = 50;
    n6->data = 60;
    n7->data = 70;
    n1->prev = NULL;
    n1->next = n2;
    n2->prev = n1;
    n2->next = n3;
    n3->prev = n2;
    n3->next = n4;
    n4->prev = n3;
    n4->next = n5;
    n5->prev = n4;
    n5->next = n6;
    n6->prev = n5;
    n6->next = n7;
    n7->prev = n6;
    n7->next = NULL;
    head = n1;
}
void display()
{
    struct node *temp = head;
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}
void delete_at_head()
{
    if (head == NULL)
        return;
    struct node *temp = head;
    head = head->next;
    if (head != NULL)
        head->prev = NULL;
    free(temp);
}
void delete_at_tail()
{
    if (head == NULL)
        return;
    struct node *temp = head;
    while (temp->next != NULL)
        temp = temp->next;
    if (temp->prev != NULL)
        temp->prev->next = NULL;
    else
        head = NULL;
    free(temp);
}
void delete_at_middle()
{
    if (head == NULL)
        return;
    printf("Enter position to delete: ");
    int position;
    scanf("%d", &position);
    if (position == 1)
    {
        delete_at_head();
        return;
    }
    struct node *temp = head;
    for (int i = 1; temp != NULL && i < position; i++)
        temp = temp->next;
    if (temp == NULL)
    {
        printf("Invalid position!\n");
        return;
    }
    if (temp->next != NULL)
        temp->next->prev = temp->prev;
    if (temp->prev != NULL)
        temp->prev->next = temp->next;
    free(temp);
}
int main()
{
    createlist();
    printf("Your Doubly Linked List is: \n");
    display();
    delete_at_head();
    printf("After deleting at head: \n");
    display();
    delete_at_tail();
    printf("After deleting at tail: \n");
    display();
    delete_at_middle();
    printf("After deleting at middle: \n");
    display();
    return 0;
}
Editor is loading...
Leave a Comment