2.6环形单链表的约瑟夫问题

版权声明:本文采用 知识共享署名4.0 国际许可协议进行许可。 https://blog.csdn.net/youmian6868/article/details/89139596
题目

用单向环形链表描述该结构并呈现整个自杀过程。

输入:一个环形单向链表的头节点head和报数的值m。

返回:最后生存下来的节点,且这个节点自己组成环形单向链表,其它节点都删掉。

代码实现
public Node josephuKill(Node head, int m) {
    if (head == null || head.next == head || m < 1) {
        return head;
    }

    Node last = head;
    while (last.next != head) {
        last = last.next;
    }

    int count = 0;
    while (head != last) {
        if (++count == m) {
            last.next = head.next;
            count = 0;
        } else {
            last = last.next;
        }
        head = last.next;
    }

    return head;
}

猜你喜欢

转载自blog.csdn.net/youmian6868/article/details/89139596