#include "iostream"
using namespace std;
class nextList
{
private:
struct Node
{
int data;
Node* next;
}*pHead;
public:
nextList() { pHead = NULL; }
~nextList();
void Print();
void Append(int num);
void Delete(int num);
void AddatBeg(int num);
void AddAfter(int c, int num);
int Count();
};
void main()
{
nextList* pobj = new nextList();
pobj->Append(11);
pobj->Append(22);
pobj->Append(33);
pobj->Delete(33);
pobj->AddatBeg(44);
pobj->AddAfter(1, 55);
pobj->Print();
cout << endl << "No. of elements in nexted list = " << pobj->Count() << endl;
delete pobj;
}
nextList::~nextList()
{
if (pHead == NULL)
return;
Node* tmp;
while (pHead != NULL)
{
tmp = pHead->next;
delete pHead;
pHead = tmp;
}
}
void nextList::Print()
{
if (pHead == NULL)
{
cout << "EMPTY";
return;
}
Node* tmp = pHead;
while (tmp != NULL)
{
cout << tmp->data << endl;
tmp = tmp->next;
}
}
void nextList::Append(int num)
{
Node* newNode;
newNode = new Node;
newNode->data = num;
newNode->next = NULL;
if (pHead == NULL)
{
pHead = newNode;
}
else
{
Node* tmp = pHead;
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = newNode;
}
}
void nextList::Delete(int num)
{
Node* tmp;
tmp = pHead;
if (tmp->data == num)
{
pHead = tmp->next;
delete tmp;
return;
}
Node* tmp2 = tmp;
while (tmp != NULL)
{
if (tmp->data == num)
{
tmp2->next = tmp->next;
delete tmp;
return;
}
tmp2 = tmp;
tmp = tmp->next;
}
cout << "\nElement " << num << " not Found.";
}
void nextList::AddatBeg(int num)
{
Node* tmp;
tmp = new Node;
tmp->data = num;
tmp->next = pHead;
pHead = tmp;
}
void nextList::AddAfter(int c, int num)
{
Node* tmp;
Node* tmp2;
int i;
for (i = 0, tmp = pHead; i < c; i++)
{
tmp = tmp->next;
if (tmp == NULL)
{
cout << endl << "There are less than " << c << " elements";
return;
}
}
tmp2 = new Node;
tmp2->data = num;
tmp2->next = tmp->next;
tmp->next = tmp2;
}
int nextList::Count()
{
Node* tmp;
int c = 0;
for (tmp = pHead; tmp != NULL; tmp = tmp->next)
c++;
return (c);
}