数据结构-单向链表实现约瑟夫

/**
 * @author zhangshiqiang on 2020/2/27.
 */
public class JosephSingleLinked {

    private int id;
    private String name;

    public JosephSingleLinked next;

    public JosephSingleLinked() {
    }

    public JosephSingleLinked(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public void add(JosephSingleLinked josephSingleLinked) {
        // 添加节点时,cur指向首节点.
        JosephSingleLinked cur = this;
        while (cur.next != null && cur.next != this) {
            cur = cur.next;
        }
        // 当前最后的节点指向添加的节点
        cur.next = josephSingleLinked;
        // 链表成环,添加的节点指向首节点
        josephSingleLinked.next = this;
    }

    public void list() {
        JosephSingleLinked cur = this;
        while (cur.next != null && cur.next != this) {
            System.out.println(cur.next);
            cur = cur.next;
        }
    }


    // 每多少个人出一个
    public void outByNum(int i) {
        // 第一个遍历的元素
        JosephSingleLinked first = this.next;
        // 指向下一个元素
        JosephSingleLinked next = null;
        while (true) {
            if (first == next) {
                break;
            }
            // 默认从1开始数
            for (int j = 1; j < i; j++) {
                next = first;
                first = first.next == this ? first.next.next : first.next;
            }
            System.out.println("出圈的元素:" + first.id);
            first = first.next == this ? first.next.next : first.next;
            next.next = first;
        }

        System.out.println("最后出圈的元素:" + first.id);
    }

    @Override
    public String toString() {
        return "JosephSingleLinked{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) {
        JosephSingleLinked singleLinked = new JosephSingleLinked();

        for (int i = 1; i <= 10; i++) {
            singleLinked.add(new JosephSingleLinked(i, "test" + i));
        }

        singleLinked.list();

        singleLinked.outByNum(3);
    }
}

猜你喜欢

转载自blog.csdn.net/now19930616/article/details/104547986