Delete last node of linked list in c++
C++ program for Delete last node of linked list. Here problem description and explanation.
// Include header file
#include <iostream>
using namespace std;
/*
C++ program for
Delete the last node of singly linked list
*/
// Linked list node
class LinkNode
{
public:
int data;
LinkNode *next;
LinkNode(int data)
{
this->data = data;
this->next = nullptr;
}
};
class SingleLL
{
public: LinkNode *head;
LinkNode *tail;
SingleLL()
{
this->head = nullptr;
this->tail = nullptr;
}
// Add new node at the end of linked list
void addNode(int value)
{
// Create a new node
LinkNode *node = new LinkNode(value);
if (this->head == nullptr)
{
this->head = node;
}
else
{
this->tail->next = node;
}
// Set new last node
this->tail = node;
}
// Display linked list element
void display()
{
if (this->head == nullptr)
{
cout << "Empty Linked List" << endl;
return;
}
LinkNode *temp = this->head;
// iterating linked list elements
while (temp != nullptr)
{
cout << temp->data << " → ";
// Visit to next node
temp = temp->next;
}
cout << "NULL" << endl;
}
// Delete last node of singly linked list
void deleteLastNode()
{
if (this->head == nullptr)
{
cout << "Empty Linked List" << endl;
return;
}
else
{
LinkNode *temp = this->head;
LinkNode *find = nullptr;
// Find second last node
while (temp->next != nullptr)
{
find = temp;
temp = temp->next;
}
if (find == nullptr)
{
// Delete head node of linked list
this->head = nullptr;
this->tail = nullptr;
}
else
{
// Set new last node
this->tail = find;
find->next = nullptr;
}
}
}
};
int main()
{
SingleLL *sll = new SingleLL();
// Linked list
// 1 → 2 → 3 → 4 → 5 → 6 → NULL
sll->addNode(1);
sll->addNode(2);
sll->addNode(3);
sll->addNode(4);
sll->addNode(5);
sll->addNode(6);
cout << "Before Delete " << endl;
sll->display();
sll->deleteLastNode();
cout << "After Delete " << endl;
sll->display();
return 0;
}
Output
Before Delete
1 → 2 → 3 → 4 → 5 → 6 → NULL
After Delete
1 → 2 → 3 → 4 → 5 → NULL
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment