01/10/2018, 00:06
Tìm lỗi sai của code bài Josephus
Em code bài Josephus như sau sai ở đâu ạ? Mong mọi người tìm giúp.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
typedef struct Dlist{
int number;
struct Dlist *prev;
struct Dlist *next;
}Dlist;
Dlist *head, *tail;
//ham chen phan tu tiep theo
void AppendNode(Dlist *inode){
if (head == NULL){
head = inode;
inode->prev = NULL;
} else{
tail->next = inode;
inode->prev = tail;
}
tail = inode;
inode->next = NULL;
}
void CreatList(int n){
Dlist *inode;
for (int i = 1; i <= n; i++){
inode = (Dlist *) malloc (sizeof(Dlist));
inode->number = i;
AppendNode(inode);
}
}
void DeleteNode(Dlist *inode){
if (inode->prev == NULL)
head = inode->next;
else inode->prev->next = inode->next;
if (inode->next == NULL)
tail = inode->prev;
else inode->next->prev = inode->prev;
}
void Josephus(int n, int m){
CreatList(n);
Dlist *count = head;
for (;;){
for (int i = 1; i < m; i++)
if (count == tail) count = head;
else
count = count->next;
if (count == tail) {
DeleteNode(count);
count = head;
}else{
count = count->next;
DeleteNode(count->prev);
if (count->next == NULL && count->prev == NULL) break;
}
}
printf("
Khach hang %i la nguoi trung thuong", count->number);
}
int main(){
int n, m;
printf("Nhap 2 so n va m: ");
scanf("%d%d",&n,&m);
Josephus(n,m);
return 1;
}
Bài liên quan
head=tail=NULL
trước khiCreatList
if (count->next == NULL && count->prev == NULL) break;
để ngoài else