魔术师发牌

  • magician
package ccnu;

public class Demo06 {

    public static void main(String[] args) {
        Node head = magician(13);
        Node p = head;
        while(p.next != head){
            System.out.print(p.data + " ");
            p = p.next;
        }
        System.out.println(p.data);
    }

    public static Node initLinkList(int n){ // 尾插法
        if(n <= 0){
            return null;
        }
        Node head = new Node();
        int i = 2;
        Node rear = head;
        while(i <= n){
            Node tmp = new Node();
            rear.next = tmp;
            rear = tmp;
            i++;
        }
        rear.next = head;
        return head;
    }

    public static Node magician(int n){
        if(n <= 0){
            return null;
        }
        Node head = initLinkList(n);
        Node p = head;
        head.data = 1;
        int cardNums = 2; // 准备设置第二张牌
        while(cardNums <= n){
            for(int i = 1; i <= cardNums; i++){ // 1 8 2 5 10 3 12 11 9 4 7 6 13
                p = p.next;
                if(p.data != 0){ // 如果当前这个节点已插入某个值,则应该跳过,即不应该计数
                    i--;
                }
            }
            p.data = cardNums;
            cardNums++;
        }
        return head;
    }
    private static class Node{
        private int data;
        private Node next = null;

        public Node(){
            this(0);
        }
        public Node(int data){
            this.data = data;
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值