Node * insertBeforeTail(Node *head, int k) {
// If the linked list is empty
if(head == nullptr){
Node* newNode = new Node(k);
return newNode;
}
//If only one node is present
if(head -> next == nullptr){
return insertBeforeTail(head, k);
}
//Normal case
Node* tail = head;
while(tail->next!=NULL){
tail = tail->next;
}
// Keep track of node before tail using prev
Node* back = tail->prev;
// Create new node with value val
Node* newNode = new Node(k);
newNode -> prev = back;
newNode -> next = tail;
// Join the new node into the doubly linked list
back->next = newNode;
tail->prev = newNode;
// Return the updated linked list
return head;
}
