Write functions insert_front and delete_front using doubly linked list.

Write functions insert_front and delete_front using doubly linked list.

Insert Front using Doubly Linked List

// insert node at the front
void insertFront(struct Node** head, int data) {

    // allocate memory for newNode
    struct Node* newNode = new Node;

    // assign data to newNode
    newNode->data = data;

    // point next of newNode to the first node of the doubly linked list
    newNode->next = (*head);

    // point prev to NULL
    newNode->prev = NULL;

    // point previous of the first node (now first node is the second node) to newNode
    if ((*head) != NULL)
        (*head)->prev = newNode;

    // head points to newNode
    (*head) = newNode;
}

Delete Front using Doubly Linked List

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node* next;
    struct node* prev;
};

struct node* head = NULL;

// Function to create a new node
struct node* createNode(int data) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->prev = NULL;
    newNode->next = NULL;
    return newNode;
}

// Function to insert a node at the front of the doubly linked list
void insertFront(int data) {
    struct node* newNode = createNode(data);
    if (head == NULL) {
        head = newNode;
        return;
    }
    head->prev = newNode;
    newNode->next = head;
    head = newNode;
}

// Function to delete a node from the front of the doubly linked list
void deleteFront() {
    if (head == NULL) {
        printf("The list is empty\n");
        return;
    }
    struct node* temp = head;
    head = head->next;
    if (head != NULL) {
        head->prev = NULL;
    }
    free(temp);
}

// Function to print the doubly linked list
void printList() {
    struct node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

// Driver program to test the doubly linked list operations
int main() {
    insertFront(4);
    insertFront(3);
    insertFront(2);
    insertFront(1);
    printf("Original List: ");
    printList();
    deleteFront();
    printf("List after deleting front node: ");
    printList();
    return 0;
}

Leave a Reply

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