Skip to content
Home » Delete last node of the singly linked list

Delete last node of the singly linked list

We can access the list only through head pointer. Next step is to traverse the list. We will keep 2 pointers. One will stop at last node and the other will stop at second last node of the list(to make address as NULL).

Below is the code to delete the last node of the singly linked list.

#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head;
void create_linked_list(int element){
struct node *temp=malloc(sizeof(struct node));
temp->data=element;
temp->next=NULL;
if(head==NULL){
head=temp;
}
else{
struct node *ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=temp;
}
}
void del_last(){
if(head==NULL){
printf("List is already empty!");
}else if(head->next==NULL){
free(head);
head=NULL;
}else{
struct node *temp=head,*temp2=head;
while(temp->next!=NULL){
temp2=temp;
temp=temp->next;
}temp2->next=NULL;
free(temp);
temp=NULL;
}
}
int main(){
create_linked_list(30);
create_linked_list(20);
create_linked_list(10);
create_linked_list(18);
del_last();
//traversing the linked list
struct node *ptr=head;
while(ptr!=NULL){
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}

OUTPUT:

30 20 10