I have to currently build a program that removes the forth student from a circle until here are none left. I have done the following code however when running it crashes with no explanation of error. Any help would be grateful and any possible explanations of the error caused.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
/*Declarations*/
int i,n,j;
struct node
{
int num;
struct node * next;
};
struct node *header, *last, *temp, *present,*previous, *first;
header = NULL;
printf("Enter how many students in the circle\n");
scanf("%d",&n);
/*create the circle of students*/
for ( i=1;i<=n;i++)
{
temp = malloc(sizeof(struct node));
temp->num=i;
if (i==1)
header = temp;
else
last -> next = temp;
last = temp;
}
/*prints of list and removes students*/
present = header;
first = present;
while (n>0)
{
for (j=0;j<3;j++)
{
if (present == NULL)
present = first;
if (j==1)
previous = present;
present = present -> next;
}
if (present == first)
first = first -> next;
/*print off each student before removing them*/
printf("%d ",present -> num);
temp = present;
previous->next = present -> next;
free(temp);
n--;
}
}