#include<iostream.h>
#include<stdio.h>
struct list
{
int info;
struct list *next;
};
class listOp
{
struct list *fPtr,*tPtr;
struct list *A,*B,*C,*T;
public:
listOp()
{
fPtr = NULL;
tPtr = NULL;
}
bool allocateNode(int); // allocate a new node & put int as its info field
struct list *traverseList(int); // travesr list & return its elements pointer
void createLoop(int element1,int element2); // create a loop between element1 & element2
bool findLoop(); // finds out whether there is loop or not
};
bool listOp::allocateNode(int info)
{
tPtr = new struct list;
if(tPtr == NULL)return false;
tPtr->info = info;
tPtr->next = NULL;
if(fPtr == NULL)
fPtr=tPtr;
else
{
struct list *t1Ptr = traverseList(-1);
t1Ptr->next = tPtr;
}
return true;
}
struct list* listOp::traverseList(int element)
{
struct list *t1Ptr = fPtr;
cout << "nThe Elements found in traversal are: n";
while(t1Ptr->next !=NULL && t1Ptr->info != element)
{
cout << t1Ptr
->info
<< "n";
t1Ptr = t1Ptr->next;
}
cout << t1Ptr
->info
<< "n";
return t1Ptr;
}
void listOp::createLoop(int element1,int element2)
{
struct list *t1Ptr = traverseList(element1);
struct list *t2Ptr = traverseList(element2);
if(t1Ptr > t2Ptr)
t1Ptr->next = t2Ptr;
else
t2Ptr->next = t1Ptr;
}
bool listOp::findLoop()
{
struct list *t1Ptr = fPtr;
struct list *t2Ptr = fPtr;
while(t1Ptr->next !=NULL)
{
t1Ptr=t1Ptr->next;
if(t2Ptr->next!=NULL)t2Ptr=t2Ptr->next;
if(t2Ptr->next!=NULL)t2Ptr=t2Ptr->next;
if(t1Ptr == t2Ptr && t2Ptr->next != NULL)
return true;
}
return false;
}
int main()
{
listOp LIST;
int choice;
int infor,infor1,infor2;
while(1)
{
cout << "nWhat operation you want to Perform: n
1. Add Node to the list. n
2. Traverse list. n
3. Create loop in the list. n
4. Find Loop. n
5. Exit. n";
cin >> choice;
switch(choice)
{
case 1: cout << "nEnter the information field of the node: ";
cin >> infor;
if(LIST.allocateNode(infor))
cout << "nNode allocated successfully";
else
cout << "nOperation Failed";
break;
case 2: cout << "nEnter the information field to which to travese: ";
cin >> infor;
LIST.traverseList(infor);
break;
case 3: cout << "nEnter element1: ";
cin >> infor1;
cout << "nEnter element2: ";
cin >> infor2;
LIST.createLoop(infor1,infor2);
break;
case 4: if(LIST.findLoop())
cout << "nLoop Found in list.";
else
cout << "nLoop not found.";
break;
default: exit(0);
}
}
return 0;
}