泫溯 2024-10-06 16:08 采纳率: 94.7%
浏览 1
已结题

(相关搜索:约瑟夫环问题)

img


int Live(CircleList head) //返回存活的人的编号
{
    int total = n;
    int j = 1;
    int count = 0;
    Node* p = (Node*)malloc(sizeof(Node));
    p = head;

    for (j; j <= n; j++)
    {
        if (total <= 2)
        {
            
            break;
        }
        p = p->next;
        count++;
        int judge = count % 3;
        if (judge) {
            DeleteList(head, count); total--;
            count = 0;
        }
    }
    return p->data;

}

请问我这个实现约瑟夫环问题的代码哪里出错了啊?

  • 写回答

1条回答 默认 最新

  • 一轮明月照丘壑 2024-10-06 16:12
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    在你的代码中,有一个错误在于当 total 等于 2 时,你需要跳出循环。这是因为当 total 等于 2 时,意味着只剩下一个节点和一个空头结点,此时应该删除列表中的最后一个元素并重置计数器为零。

    以下是修改后的代码:

    int Live(CircleList head) //返回存活的人的编号
    {
        int total = n;
        int j = 1;
        int count = 0;
        Node* p = (Node*)malloc(sizeof(Node));
        p = head;
    
        while (total > 2)
        {
            if (total == 2)
            {
                break;
            }
    
            p = p->next;
            count++;
            int judge = count % 3;
            if (judge) {
                DeleteList(head, count); total--;
                count = 0;
            }
        }
    
        return p->data;
    }
    

    现在,当 total 等于 2 时,循环将停止,并且不会尝试删除任何元素。这样可以确保正确地处理所有情况,并返回正确的结果。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月15日
  • 已采纳回答 10月7日
  • 创建了问题 10月6日