I am working on the program which solves Josephus problem on C. I have to use circular linked lists here. Currently I have this code to create list:
void create_list(int N, struct node* head){
int i, j, k;
for(i = 2; i <= N; i++){
struct node* tmp_node = (struct node*)malloc(sizeof(struct node));
tmp_node -> number = i;
tmp_node -> next = NULL;
tmp_node -> next = head -> next;
head -> next = tmp_node;
head = tmp_node;
}
}
Now I am working on finding last element to remin after Josephus permutations. I have this:
int find_last(int M, struct node* head){
int i, j = 1;
if(head -> next == NULL){
return head -> number;
}
else {
struct node* current = head;
while(current -> next != NULL){
while(current -> next -> number != j){
current = current -> next;
j++;
}
if (j % M == 0){
struct node* delete_node;
delete_node = current -> next;
current -> next = delete_node -> next;
free(delete_node);
j = 1;
}
}
return current -> number;
}
}
And this is my main:
int main(){
int M, N, i, j, res;
struct node* head = (struct node*)malloc(sizeof(struct node));
head -> number = 1;
head -> next = NULL;
read_numbers(&N, &M);
create_list(N, head);
res = find_last(M, head);
printf("%d\n", res);
return 0;
}
The problem occurs in int find_last function. Please, tell me the errors and what I can do to solve the problem, thanks for your time.
EDIT.
I have drawn the algorithm and updated my function but it still doesn't work. Here it is:
int find_last(int M, int N, struct node* head){
int i = 0, j = 1;
if(head -> next == NULL){
return head -> number;
}
else {
struct node* current = head;
while(i != N){
while(j % M != 0){
current = current -> next;
j++;
}
struct node* delete;
delete = current -> next;
delete -> next = current -> next;
free(delete);
i++;
}
return current -> number;
}
}
create_list()
does NOT create a circular LL. You'll have to examine the code to see your own mistake there. The shortest explanation would take longer to relate than merely fixing the code.Shorter (working!) code to study:
You can get yourself tied up in knots with verbiage and without planning.
Caveat:
M
down count may be off-by-one. Change--i
toi--
to suit your interpretation of how far to travel around the shrinking ring of nodes.EDIT
After closer examination, I believe the following is a better version. (No changes to
create()
shown above.)