Implement Node class in C++, which can store an integer data and a pointer to next node. Make
sure you define constructor of the class to initialize data member(s).
#include<iostream>
using namespace std;
class LinkedList
{
private:
struct LinkListNodes
{
int value;
LinkListNodes *next;
};
LinkListNodes*head;
public:
LinkedList();
~LinkedList();
void AppendNodes(int);
void InsertNodes(int);
void DeleteNodes(int);
void DisplayNodes(void);
};
LinkedList::LinkedList()
{
head = NULL;
}
LinkedList::~LinkedList()
{
LinkListNodes *NodePtr,*NextNode;
NodePtr=head;
while(NodePtr)
{
NextNode=NodePtr->next;
delete NodePtr;
NodePtr=NextNode;
}
}
void LinkedList::AppendNodes(int num)
{
LinkListNodes *NodePtr, *NewNode;
NewNode = new LinkListNodes;
NewNode->value = num;
NewNode->next = NULL;
if (!head)
{
head = NewNode;
}
else
{
NodePtr = head;
while (NodePtr->next)
{
NodePtr = NodePtr->next;
}
NodePtr->next = NewNode;
}
}
void LinkedList::InsertNodes(int num)
{
LinkListNodes *PreNode, *NodePtr, *NewNode;
NewNode = new LinkListNodes;
NewNode->value = num;
if (!head)
{
head = NewNode;
NewNode->next = NULL;
}
else
{
NodePtr = head;
PreNode=NULL;
while (NodePtr != NULL && NodePtr->value < num)
{
PreNode = NodePtr;
NodePtr = NodePtr->next;
}
if (PreNode == NULL)
{
head = NewNode;
NewNode->next = NodePtr;
}
else
{
PreNode->next = NewNode;
NewNode->next = NodePtr;
}
}
}
void LinkedList::DeleteNodes(int num)
{
LinkListNodes *NodePtr, *PreNode;
if (!head)
{
return;
}
if (head->value == num)
{
NodePtr = head->next;
delete head;
head = NodePtr;
}
else
{
NodePtr = head;
while (NodePtr != NULL && NodePtr->value != num)
{
PreNode = NodePtr;
NodePtr = NodePtr->next;
}
PreNode->next = NodePtr->next;
delete NodePtr;
}
}
void LinkedList::DisplayNodes(void)
{
LinkListNodes *NodePtr;
cout << "Liked List Nodes Value are: " << endl;
NodePtr = head;
while (NodePtr!=NULL)
{
cout << "Address "<<&NodePtr->value<<" Value Is : "<<NodePtr->value <<" "<< "\tNext Address :" <<NodePtr->next<< endl;
NodePtr = NodePtr->next;
}
}
int main()
{
LinkedList l;
l.InsertNodes(6);
l.InsertNodes(2);
l.InsertNodes(10);
l.InsertNodes(23);
l.DisplayNodes();
}