deletion in a doubly linked list:

  Doubly Linked List:

 A doubly linked list is a type of data structure(self-referential structures). Each node in the doubly linked list consists of three parts, namely the data and the reference to the next node, and the reference to the previous node.



deletion in a doubly-linked list:

In doubly linked list deletion takes place in different ways that are ;

  • deletion from the end/last node
  • deletion from nth node

delete the last node of the doubly linked list:

   

void Del_last(int key)
    {
        if (head != NULL)
        {
            DNode* previousToLast, * lastNode, * temp;
            previousToLast = NULL;
            lastNode = NULL;
            if (head->data == key)
                lastNode = head;
            temp = head;
            while (temp->next != NULL)
            {
                if (temp->next->data == key)
                {
                    previousToLast = temp;
                    lastNode = temp->next;
                }
                temp = temp->next;
            }
            if (lastNode != NULL)
            {
                if (lastNode == head)
                {
                    head = head->next;
                    free(lastNode);
                }
                else {
                    previousToLast->next = lastNode->next;
                    if (previousToLast->next != NULL)
                        previousToLast->next->prev = previousToLast;
                    free(lastNode);
                }
            }
        }
    }

delete nth node of  doubly linked list:

  void Del_NthNode(int position) {
        if (position < 1) {
            cout << "\nposition should be >= 1.";
        }
        else if (position == 1 && head != NULL) {
            DNode* nodeToDelete = head;
            head = head->next;
            free(nodeToDelete);
            if (head != NULL)
                head->prev = NULL;
        }
        else {
            DNode* temp = head;
            for (int i = 1; i < position - 1; i++) {
                if (temp != NULL) {
                    temp = temp->next;
                }
            }
            if (temp != NULL && temp->next != NULL) {
                DNode* nodeToDelete = temp->next;
                temp->next = temp->next->next;
                if (temp->next->next != NULL)
                    temp->next->next->prev = temp->next;
                free(nodeToDelete);
            }
            else {
                cout << "\nThe node is already null.";
            }
        }
    }


Comments

Popular Posts