您的位置:首页 > 其它

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

2015-11-09 13:57 453 查看
大神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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: