im solving a problem in linked list.how to check loop inside a linked list.
i ve done implentation. always it goes without any error. but sometimes it encounters
segmentation error. i dont find wny error or warning other than that.please try to help me figure out
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*
* structure for the linkedlist node
*/
typedef struct node *ptr;
typedef ptr list;
typedef struct listnode *hcell;
typedef hcell cell;
typedef struct hashtable *hashtbl;
struct node
{
int ele; //element
struct node *next;//next pointer
};
/*
* opening the file for input
*/
void Hasloop(int);
struct listnode
{
unsigned int lielement;
struct listnode *nextele;
};
struct hashtable
{
cell *lists;
int tablesize;
};
list l;
hashtbl h;
int num;
int nextPrime(int n)
{
int m=0,flag=0,i=0;
while(m==0)
{
flag=0;
for(i=2;i<n;i++)
{
if(n%i==0)
{
flag=1;
n++;
break;
}
}
if(flag==0)
{
m++;
}
}
return n;
}
void initialize()
{
int tsize=15,i=0;
h=malloc(sizeof(struct hashtable));
h->tablesize=nextPrime(15);
h->lists=malloc(sizeof(struct listnode)*15);
for(i=0;i<tsize;i++)
{
h->lists[i]=malloc(sizeof(struct listnode));
h->lists[i]->nextele=NULL;
}
}
int hash(unsigned int e)
{
int i=0;
i=e%h->tablesize;
return i;
}
cell find(int e)
{
cell pc=h->lists[hash(e)];
cell lc=pc->nextele;
while(lc!=NULL && lc->lielement!=e)
lc=lc->nextele;
return lc;
}
void insert( unsigned int l)
{
int i;
int emsg=0;
cell pos,newcell,lc,gc,cc;
lc=h->lists[hash(l)];
if(lc->lielement!=l || lc->lielement==0)
{
lc->lielement=l;
lc->nextele=NULL;
}
else
{
printf("Came here");
emsg=1;
Hasloop(emsg);
}
}
void Createlinklist()
{
FILE *fp;
int *f;
fp=fopen("input.txt","r");
int i=0,e=0;
fscanf(fp,"%d",&num);
list p,o,k;
while(num!=i)
{
fscanf(fp,"%d",&e);
if(i==0)
{
l=malloc(sizeof(struct node));
l->ele=e;
l->next=NULL;
p=l;
}
else
{
p->next=malloc(sizeof(struct node));
p->next->ele=e;
p->next->next=NULL;
p=p->next;
}
i++;
}
o=l;
k=l;
while(k->next!=NULL)
k=k->next;
while(o->next!=NULL && o->ele!=65)
o=o->next;
k->next=o;
}
void Hasloop(int e)
{
list o,k;
o=l;
k=l;
if(e==1)
{
printf("Loop exists ......Terminating program\t\t\t[\tOK\t]\t\n");
exit(0);
}
else if(k->next==o)
{
printf("Loop exists between start and end node ......Terminating program\t\t\t[\tOK\t]\n");
exit(0);
}
}
void Displaylist()
{
list p;
cell gc;
p=l;
int i=0,j=0;
printf("\nStarting address:\n");
while(p!=NULL)
{
printf("[%d]==>%u\n",p->ele,(unsigned int)&p->ele);
i++;
p=p->next;
if(i>5)
break;
}
i=0;
p=l;
printf("\n\n");
printf("\nNext pointer address:\n");
while(p!=NULL)
{
if(i==0)
insert((unsigned int)&p->ele);
if(j<num)
insert((unsigned int)p->next);
printf("[%d]==>%u\n",p->ele,(unsigned int)p->next);
p=p->next;
i++;
j++;
if(i>25)
break;
}
i=0;
while(i<15)
{
gc=h->lists[i];
printf("%d\n",gc->lielement);
i++;
}
}
void main()
{
initialize();
Createlinklist();
//hasloop();
Displaylist();
}