Thursday, September 15, 2016

Create and check a loop in a linked list in C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
struct node *temp=NULL;
int gLoopCounter;
void insert()
{
int lData=0;
struct node *temp1;
printf("Please enter data:\t");
scanf("%d",&lData);
temp=malloc(sizeof(struct node *));
temp1=start;

if(temp1 == NULL )
{
start=temp;
temp->data=lData;
temp->next=NULL;
gLoopCounter++;
}
else
{
printf("here1\n");
while(temp1->next != NULL)
{
temp1=temp1->next;
}
gLoopCounter++;
if(gLoopCounter == 3)
{
temp1->next=temp;
temp->data=lData;
temp->next=temp1;
}
else
{
temp1->next=temp;
temp->data=lData;
temp->next=NULL;
}
}
}

void checkLoop()
{
struct node *temp=start;
while(1)
{
if(temp->next->next == temp)
{
printf("Loop Found at node with data [%d]\n",temp->next->data);
break;
}
else
temp=temp->next;
}
}
int main()
{
int choice;
printf("note -------------Enter only 3 nodes\n");
while(1)
{
printf(" 1. Insert and create loop at 3rd node \n 2. Check for loop \n 3. Exit\n\n Enter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
checkLoop();
break;
case 3:
exit(0);
break;
default:
printf("Invalid choice\n");
break;
}
}
return 0;
}

No comments:

Post a Comment