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.


 Live Demo

using namespace std;
class node{
   int data;
   node(int d){
      node*next= NULL;
void insertAtFirst(node*&head, int data){
   node*n= new node(data);
   n->next= head;
void printNode(node*head){
void deleteatTail(node*head){
   node*prev= NULL;
   node*temp= head;
      prev= temp;
   delete temp;
   prev->next= NULL;
int main(){
   node*head= NULL;


Running the above code will generate the output as,


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 →.

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