10人围成圈 0123 remove(3)

package com.ctc.iasms.base.region.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FindLast {

    public static int findTheLastOne(int totalNum, int count) {

        List<Integer> _list = new ArrayList<Integer>();

        for (int i = 1; i <= totalNum; i++) {
            _list.add(i);
        }
        Iterator<Integer> _it = _list.iterator();
        int _currentCount = 0;
        do {
            if (_it.hasNext()) {
                _it.next();
                _currentCount++;
                if (_currentCount == count) {
                    _it.remove();
                    _currentCount = 0;
                }
            } else {
                _it = _list.iterator();
            }
        } while (_list.size() > 1);
        return _list.get(0);
    }

    public static void main(String[] args) {
        int _lastIndex = findTheLastOne(10, 3);
        System.out.println(_lastIndex);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是经典的约瑟夫问题,其解法可以用循环链表和递归两种方式实现。以下是用循环链表实现的C语言代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; } Node; Node* create(int n) { Node* head = (Node*)malloc(sizeof(Node)); head->data = 1; head->next = NULL; Node* tail = head; for (int i = 2; i <= n; i++) { Node* node = (Node*)malloc(sizeof(Node)); node->data = i; node->next = NULL; tail->next = node; tail = node; } tail->next = head; // 将链表的尾节点指向头节点,形成循环链表 return head; } Node* remove(Node* head, int k) { Node* p = head; while (p->next != p) { // 当链表中只剩一个节点时结束循环 for (int i = 1; i < k; i++) { p = p->next; } Node* temp = p->next; p->next = temp->next; // 将当前节点的下一个节点从链表中删除 free(temp); // 释放被删除节点的内存 } return p; } int main() { int n = 10; int k = 3; Node* head = create(n); Node* p = remove(head, k); printf("The last one is %d\n", p->data); free(p); // 释放最后一个节点的内存 return 0; } ``` 这段代码中,`create`函用于创建一个有`n`个节点的循环链表,并返回头节点的指针。`remove`函用于从循环链表中每隔`k-1`个节点删除一个节点,直到链表中只剩下一个节点,最后返回最后一个节点的指针。在主函中,我们调用`create`函创建了一个有`10`个节点的循环链表,然后调用`remove`函从链表中每隔`2`个节点删除一个节点,最后输出剩下的最后一个节点的编号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值