其他分享
首页 > 其他分享> > 单向环形链表

单向环形链表

作者:互联网

joseph问题

单向环形链表

节点类

class Node {
    public int id;
    public Node next;

    @Override
    public String toString() {
        return "Node{" +
                "id=" + id +
                '}';
    }

    public Node(int id) {
        this.id = id;
    }
}

链表类

class CircleSingleLinkedList {
    private Node first = null;

    // 报数出圈
    public void countNode(int startId, int countNum, int nums) {
        if (isEmpty() || startId < 1 || startId > nums) {
            System.out.println("参数不合法");
            return;
        }
        // 定义辅助指针指向first前面
        Node helper = first;
        while (true) {
            if (helper.next == first) {
                break;
            }
            helper = helper.next;
        }
        // 此时辅助指针指向first前一个节点
        // 报数前,先将两个指针移动到startId
        for (int i = 0; i < startId - 1; i++) {
            first = first.next;
            helper = helper.next;
        }
        // 循环报数
        while (true) {
            if (first == helper) {
                break;
            }
            // 将辅助指针移动countNum - 1次
            for (int i = 0; i < (countNum - 1); i++) {
                first = first.next;
                helper = helper.next;
            }
            // 此时first指向的节点就是要出圈的节点
            System.out.println(first + "出圈");
            // 出圈
            first = first.next;
            helper.next = first;
        }
        System.out.println("最后留下的是" + first);
    }


    // 创建nums个节点
    public void addNodes(int nums) {
        if (nums < 1) {
            System.out.println("nums不合法");
            return;
        }
        // 辅助指针
        Node cur = null;
        for (int i = 1; i <= nums; i++) {
            // 创建
            Node node = new Node(i);
            // 插入
            // 如果是第一个
            if (i == 1) {
                first = node;
                // 构成环状
                first.next = first;
                // cur移动
                cur = first;
            } else {
                cur.next = node;
                node.next = first;
                // cur移动
                cur = node;
            }
        }
    }

    // 遍历
    public void show() {
        if (isEmpty()) {
            System.out.println("没有任何小孩");
            return;
        }
        Node cur = first;
        while (true) {
            System.out.println(cur.id);
            if (cur.next == first) {
                break;
            }
            // cur右移
            cur = cur.next;
        }
    }

    private boolean isEmpty() {
        return first == null;
    }
}

测试类

public class Joseph {
    public static void main(String[] args) {
        CircleSingleLinkedList list = new CircleSingleLinkedList();
        list.addNodes(5);
        list.countNode(1,2,5);
    }
}

标签:Node,helper,int,单向,环形,next,链表,public,first
来源: https://www.cnblogs.com/coderDreams/p/16061849.html