• 约瑟夫问题


    一、约瑟夫问题

       1.问题叙述:   

                      

         2.解题思路

            1)构建含有41个结点的单链表,分别存储1-41的值,代表着41个人

            2)使用计数器count,记录当前的值 

            3)遍历链表,每循环一次链表++

            4)判断count的值,如果为三则删除此结点,count置为0

    public class JoseTest{
        public static void main(String[] args) {
            //定义首结点
            Node<Integer> first =null;
            Node<Integer> pre = null;
            //定义循环链表
            for (int i=1;i<=41;i++){
                //1.如果是第一个结点
                if(i==1){
                    first = new Node<>(i, null);
                    pre=first;
                    continue;
                }
                //2.如果不是第一个,创建新结点
                Node<Integer> newNode = new Node<>(i, null);
                //让上一个结点指向当前结点
                pre.next=newNode;
                //重置pre,让pre代表当前结点
                pre=newNode;
                //如果为41个结点时
                if(i==41){
                    pre.next=first;
                }
            }
            //模拟报数
            int count=0;
            //遍历循环链表
            Node<Integer> n=first;
    
            Node<Integer> before=null;
            while (n!=n.next){
                count++;
                if(count==3){
                    //删除该结点,n的上一个结点指向下一个结点
                    before.next=n.next;
                    System.out.print(n.item+",");
                    //重置count
                    count=0;
                    n=n.next;
                }else{
                    before=n;
                    n=n.next;
                }
            }
            //最后一个元素
            System.out.println(n.item);
        }
    
        public static class Node<T>{
            T item;
            Node next;
    
            public Node(T item, Node next) {
                this.item = item;
                this.next = next;
            }
        }
    }
  • 相关阅读:
    什么是linux的ftp
    linux安装ftp组件
    菜鸟之linux问题之图形界面和dos界面的登录问题
    linux第一面
    vmware下linux系统的安装过程
    vmware的安装
    装饰器的邪门歪道
    关于任务脚本里面用异步
    写类装饰器的2个小问题
    VUE 与其他常见前端框架对比
  • 原文地址:https://www.cnblogs.com/cqyp/p/12568681.html
Copyright © 2020-2023  润新知