1号 到 100号 数数 123 数到 3 退出 最后剩下几号

来源:互联网 发布:农民资金合作社软件 编辑:程序博客网 时间:2024/05/16 04:47

大神fookwood提供的思路:写个循环链表,模拟删除操作。

public class Count123 {    public static void main(String[] args){        Node node = Node.initCycle(10);        int count = 1;        while(node.next != node){            Node temp = node.next;            count++ ;            //如果下个节点数到3,删除下个节点            if(count==3){                node.next=temp.next;                count = 0;                continue;            }            node = temp;        }        System.out.println(node.index);    }}//链表节点class Node{    int index;    Node next;    Node(int index){        this.index = index;    }    //初始化链表    static Node initCycle(int n){        Node node = new Node(1);        Node re = node;        for(int i=2;i<n+1;i++){            Node temp = new Node(i);            node.next = temp;            node = temp;            //最后一个节点的next指向第一个节点            if(i==n){                node.next = re;            }        }        return re;    }}
0 0
原创粉丝点击