How to delete a node from the end of linked list
DeleteFromEnd() deletes the last node in the linked list.
Summary of DeleteFromEnd()
There are 3 cases to consider while deleting a node from the end of the linked list:
1. If the linked list is empty.
2. If the linked list consists of only 1 node.
3. If the linked list contains more than 1 node.
First case
If the linked list is empty, then a message is displayed that:
“Linked List already empty”
Second case
If the linked list consists of only 1 node then the head is deleted and assigned a NULL.
Third case
If the linked list consists of more than 1 node, then the whole linked list is traversed upto the second last node, when the second last node comes its link pointer is assigned a NULL and the address of the last node is saved in a pointer tptr and at the end it is deleted.
Code of DeleteFromEnd()
void LinkList::DeleteFromEnd()
{
if(head==NULL)
{
cerr<<"Linked List already empty"<<endl;
}
else if(head->link==NULL)
{
delete head;
head=NULL;
}
else
{
Node*temp=head;
while(temp->link->link!=NULL)
temp=temp->link;
Node*tptr=temp->link;
temp->link=NULL;
delete tptr;
}
}
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
struct Node
{
public:
int data;
Node*link;
Node();
};
Node::Node()
{
data=0;
link=NULL;
}
class LinkList
{
public:
Node*head;
LinkList();
void AddNodeAtEnd(int);
void DeleteFromEnd();
void DisplayWhole();
};
LinkList::LinkList()
{
head=NULL;
}
void LinkList::AddNodeAtEnd(int _data)
{
Node*node=new Node();
node->data=_data;
node->link=NULL;
if(head==NULL)
head=node;
else
{
Node*tptr=head;
while(tptr->link!=NULL)
tptr=tptr->link;
tptr->link=node;
}
}
void LinkList::DeleteFromEnd()
{
if(head==NULL)
{
cerr<<"Linked List already empty"<<endl;
}
else if(head->link==NULL)
{
delete head;
head=NULL;
}
else
{
Node*temp=head;
while(temp->link->link!=NULL)
temp=temp->link;
Node*tptr=temp->link;
temp->link=NULL;
delete tptr;
}
}
void LinkList::DisplayWhole()
{
Node*temp=head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
}
int main()
{
LinkList l;
// Adding first element to end of the linked list
l.AddNodeAtEnd(10);
// Adding second element to end of the linked list
l.AddNodeAtEnd(20);
// Adding third element to end of the linked list
l.AddNodeAtEnd(30);
// Adding fourth element to end of the linked list
l.AddNodeAtEnd(40);
// Adding fifth element to end of the linked list
l.AddNodeAtEnd(50);
// Displaying all nodes in the linked list
cout<<"Linked list : "<<endl;
l.DisplayWhole();
cout<<endl;
l.DeleteFromEnd();
// Displaying all nodes in the linked list
cout<<"Linked list after deleting the last node : "<<endl;
l.DisplayWhole();
cout<<endl;
_getche();
return 0;
}
Ouptut
Linked list :
10
20
30
40
50
Linked list after deleting the last node :
10
20
30
40
0 comments:
Post a Comment