希望大家可以帮我看看
typedef int ElemType;
typedef int Status;
typedef struct QNode {
int id;
struct QNode* next;
} QNode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue& Q);
Status DestroyQueue(LinkQueue& Q);
Status ClearQueue(LinkQueue& Q);
Status QueueEmpty(LinkQueue& Q);
int QueueLength(LinkQueue& Q);
QueuePtr GetHead(LinkQueue& Q,ElemType &e);
Status EnQueue(LinkQueue& Q,ElemType e);
Status DeQueue(LinkQueue& Q,ElemType &e);
void visit(LinkQueue Q);
Status QueueTraverse(LinkQueue Q,void visit(LinkQueue Q));
void Josephus(LinkQueue& Q, int k, int m);
Status InitQueue(LinkQueue& Q){
Q.front=(QueuePtr)malloc(sizeof(QNode));
if(!Q.front) {
printf("初始化失败\n");
exit(OVERFLOW);
}
Q.front->next=NULL;
return OK;
}
Status DestroyQueue(LinkQueue& Q){
while(Q.front){
Q.rear=Q.front->next;
free(Q.front) ;
Q.front=Q.rear;
}
return OK;
}
Status ClearQueue(LinkQueue& Q){
QueuePtr p = Q.front;
while (p) {
QueuePtr temp = p->next;
free(p);
p = temp;
}
if (Q.front== Q.rear) return ERROR;
return OK;
}
Status QueueEmpty(LinkQueue& Q){
return Q.front == Q.rear;
}
int QueueLength(LinkQueue& Q) {
int count = 0;
QueuePtr p = Q.front->next;
while (p) {
count++;
p = p->next;
}
return count;
}
QueuePtr GetHead(LinkQueue& Q, ElemType &e) {
if (Q.front == Q.rear) return NULL;
e = Q.front->next->id;
return Q.front->next;
}
Status EnQueue(LinkQueue& Q,ElemType e){
QueuePtr p ;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p) exit(OVERFLOW);
p->id=e; p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return OK;
}
Status DeQueue(LinkQueue& Q,ElemType &e){
if (Q.front== Q.rear) return ERROR;
QueuePtr p ;
p=Q.front->next;
e=p->id;
Q.front->next=p->next;
if (p== Q.rear) Q.rear==Q.front ;
free(p);
return OK;
}
void visit(QueuePtr p) {
printf("%d ", p->id);
}
Status QueueTraverse(LinkQueue Q, void (*visit)(QueuePtr)) {
QueuePtr p = Q.front->next;
while (p) {
visit(p);
p = p->next;
}
printf("\n");
return OK;
}
void Josephus(LinkQueue& Q, int k, int m) {
QueuePtr p = Q.front;
// 移动到开始报数的位置
for (int i = 0; i < k - 1; i++) {
p = p->next;
}
// 开始报数
while (QueueLength(Q) > 0) {
for (int i = 1; i < m; i++) {
p = p->next;
if (p == Q.front) p = p->next; // 跳过头节点
}
// p指向的节点出列
QueuePtr temp = p->next;
printf("出列的人是:%d\n", temp->id);
p->next = temp->next;
if (temp == Q.rear) Q.rear = p; // 如果出列的是尾节点,则更新尾节点
free(temp);
if (p->next == Q.front) p = p->next; // 如果下一个节点是头节点,则跳过头节点
}
}
int main() {
LinkQueue Q;
int n, k, m;
printf("请输入人数n、开始报数的位置k和数到m的人出列:");
scanf("%d %d %d", &n, &k, &m);
InitQueue(Q);
for (int i = 1; i <= n; i++) {
EnQueue(Q, i);
}
Josephus(Q, k, m);
DestroyQueue(Q);
return 0;
}
//file.h