Delete a tail node from the given singly Linked List using C++

C++Server Side ProgrammingProgramming

A Linked List is a linear Data Structure that contains nodes and each node has two fields; one is the value or data to be inserted and the other field stores the address of the next node.

Our task here is to delete a node from the end of a Linked List. The last node is known as the tail node. If there is no node in the Linked List, then return NULL.

For example −

Input 1 − 1 → 2 → 3 → 4 → 5

Output − 1 → 2 → 3 → 4 →

Explanation − In the given singly linked list, the node from the end is ‘5’. After deleting the last node, the output will be, 1 → 2 → 3 → 4 →.

Input 2 − 5 → 8 →3

Output − 5 → 8 →

Explanation − In the given singly linked list, the node from the end is ‘3’. After deleting the node from the end, the output will be, 5 →8 →.

Approach to solve this problem

The simple approach to solve this particular problem is to create a previous node that later on stores the value of the current node when the current pointer will point to the last node of the linked list.

Iterate over all the nodes of the linked list if the current node points to the last node. And finally, return from the linked list.

  • Initialize the linked list by inserting the nodes into it.

  • Function insertAtFirst(node*&head, int data) will insert all the nodes in the linked list.

  • A function deleteAtTail(node*head) takes a pointer that is currently pointing to the head.

  • Create a previous Node pointer and initialize it as NULL.

  • Create a temporary Node pointer that is currently pointing to the head of the pointer.

  • Traverse the temporary pointer until it does not reach the end of the linked list.

  • Store the value of the temporary pointer in the previous node pointer.

  • Delete the temporary pointer.

  • Return the linked list.

Example

 Live Demo

#include<iostream>
using namespace std;
class node{
   public:
   int data;
   node*next;
   node(int d){
      data=d;
      node*next= NULL;
   }
};
void insertAtFirst(node*&head, int data){
   node*n= new node(data);
   n->next= head;
   head=n;
}
void printNode(node*head){
   while(head!=NULL){
      cout<<head->data<<"->";
      head=head->next;
   }
   cout<<endl;
}
void deleteatTail(node*head){
   node*prev= NULL;
   node*temp= head;
   while(temp->next!=NULL){
      prev= temp;
      temp=temp->next;
   }
   delete temp;
   prev->next= NULL;
   return;
}
int main(){
   node*head= NULL;
   insertAtFirst(head,5);
   insertAtFirst(head,4);
   insertAtFirst(head,3);
   insertAtFirst(head,2);
   insertAtFirst(head,1);
   deleteatTail(head);
   printNode(head);
}

Output

Running the above code will generate the output as,

1→2→3→4→

In the given input singly linked list, 1 → 2 → 3 → 4 → 5, the last node of the linked list is ‘5’. Hence, after deletion of the last node, the linked list will become 1 → 2 → 3 → 4 →.

raja
Published on 05-Feb-2021 07:18:08
Advertisements