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

## Example

Live Demo

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