This is my code to append an integer in linked list.
#include "iostream"
using namespace std;
class LinkList
{
private:
struct Node
{
int data;
Node* link;
}*p;
public:
LinkList();
~LinkList();
void Print(); // Prints the contents of linkedlist
void Append(int num); // Adds a new node at the end of the linkedlist
void Delete(int num); // Deletes the specified node from the linkedlist
void AddatBeg(int num);// Adds a new node at the beginning of the linkedlist
void AddAfter(int c, int num); // Adds a new node after specified number of nodes
int Count(); // Counts number of nodes present in the linkedlist
};
LinkList::LinkList()
{
p = NULL;
}
LinkList::~LinkList()
{
if (p == NULL)
return;
Node* tmp;
while(p != NULL)
{
tmp = p->link ;
delete p;
p = tmp;
}
}
// Prints the contents of linkedlist
void LinkList::Print()
{
if (p == NULL)
{
cout<< "EMPTY";
return;
}
//Traverse
Node* tmp = p;
while(tmp != NULL)
{
cout<<tmp->data<<endl;
tmp = tmp->link ;
}
}
// Adds a new node at the end of the linkedlist
void LinkList::Append(int num)
{
Node *newNode;
newNode = new Node;
newNode->data = num;
newNode->link = NULL;
if(p == NULL)
{
//create first node
p = newNode;
}
else
{
//Traverse
Node *tmp = p;
while(tmp->link != NULL)
{
tmp = tmp->link;
}
//add node to the end
tmp->link = newNode;
}
}
// Deletes the specified node from the linkedlist
void LinkList::Delete( int num )
{
Node *tmp;
tmp = p;
//If node to be delete is first node
if( tmp->data == num )
{
p = tmp->link;
delete tmp;
return;
}
// traverse list till the last but one node is reached
Node *tmp2 = tmp;
while( tmp!=NULL )
{
if( tmp->data == num )
{
tmp2->link = tmp->link;
delete tmp;
return;
}
tmp2 = tmp;
tmp = tmp->link;
}
cout<< "\nElement "<<num<<" not Found." ;
}
int LinkList::Count()
{
Node *tmp;
int c = 0;
//Traverse the entire Linked List
for (tmp = p; tmp != NULL; tmp = tmp->link)
c++;
return (c);
}
int main()
{
LinkList* pobj = new LinkList();
pobj->Append(11);
pobj->Print();
delete pobj;
return 0;
}
What I am looking for is a code where I can insert elements of arrays in linked list. For example, if there are two arrays containing elements (1,2,3) and (4,5,6), Code should create two Linked lists and the address of first node of each linked list should be stored in an array so that running a for loop would print all linked list in sequence. Example:
Linked List 1 = (1,2,3)
Linked List 2 = (4,5,6)
Number of arrays and number of elements inside arrays will be dynamic.