I have modified the code to take care of head data and link pointing to NULL.
Code:
#include<stdlib.h>
#include<stdio.h>
typedef struct Node Node;
typedef struct Set Set;
struct Node
{
int data;
struct Node *link;
};
struct Set
{
struct Node *head;
};
Set *set_create()
{
Set *set = malloc(sizeof(*set));
if(set ==NULL)
{
printf("Sorry !! Memory Full :)");
}
else
set->head = NULL;
return set;
}
Node *append(Set *set,int value)
{
Node *node;
node = malloc(sizeof(*node));
node->data=value;
node->link=NULL;
if(set->head == NULL)
{
set->head = node;
}
else
{
Node *iter = set->head;
while(iter->link)
{
iter=iter->link;
}
iter->link=node;
}
return node;
}
void traverse(Set *set)
{
const Node *node = set->head;
while(node)
{
printf("%d\n",node->data);
node=node->link;
}
}
int nextPrime(int num)
{
if(num==1 || num ==0)
return 2;
num++;
int i;
int flag;
for(i=2;i<=num/2;++i)
{
if(num%i==0)
{
flag=0;
break;
}
}
if(flag==0)
return nextPrime(num);
else
return num;
}
void destroy(Set *one)
{
Node *node = one->head;
while(node)
{
Node *next = node->link;
free(node);
node=next;
}
}
void calculateFactors(int number, Set *one)
{
int Den,reminder;
Den = nextPrime(0);
while(number >1 )
{
reminder = number % Den;
if(reminder != 0)
{
Den=nextPrime(Den);
//printf("%d\n",Den);
}
else
{
// printf("%d\t",Den);
number=number / Den;
//printf("%d\n",Den);
append(one,Den);
}
}
}
void main()
{
int number;
scanf("%d",&number);
Set *factors=set_create();
calculateFactors(number,factors);
traverse(factors);
//destroy(factors);
}
Thep program just prints out the factors of a number. I wanted to use a linked list so that I could be more familiar with it.
The program works just fine for most of the inputs I'e tried but fails unexpectedly for a few one.
Suppose i give the input as 157, for which the program needs to find out the factors, the program fails. I tried with print statements in the calculateFactors function to check if the values are correctly calculated. Turns out all the values are calculated fine but fails in the append statement in the calculateFactors function. Any guesses as to why this happens?