数据结构与算法-1.5约瑟夫问题(循环单向列表)

约瑟夫问题(java版)

package hello;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YueSeFu {

    public static void main(String[] args) {
        List<Page> list = new ArrayList<>();
        for (int i = 0; i < 41; i++) {
            Page page = new Page();
            page.setData(i+1);
            page.setNextPage(i+1);
            list.add(page);
        }
        list.get(list.size()-1).setNextPage(0);
        method1(list, 3,list.size());

    }
    
    public static void method1(List<Page> arr,int num,int totalPerson ){
        int flag = 0;
        int count = 0;
        while (count!=totalPerson) {
            for (int i = 0; i < arr.size(); i++) {
                if (arr.get(i).getNextPage()==-1) {
                    continue;
                }
                flag += 1;
                if (flag % num == 0) {
                    arr.get(i).setNextPage(-1);
                    count+=1;
                    System.out.print(arr.get(i).getData()+"--");
                }
            }
            
        }
    }

}

Page类



package hello;

public class Page {
    
    private Integer data;
    private Integer nextPage;
    
    public Integer getData() {
        return data;
    }
    public void setData(Integer data) {
        this.data = data;
    }
    public Integer getNextPage() {
        return nextPage;
    }
    public void setNextPage(Integer nextPage) {
        this.nextPage = nextPage;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((data == null) ? 0 : data.hashCode());
        result = prime * result + ((nextPage == null) ? 0 : nextPage.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Page other = (Page) obj;
        if (data == null) {
            if (other.data != null)
                return false;
        } else if (!data.equals(other.data))
            return false;
        if (nextPage == null) {
            if (other.nextPage != null)
                return false;
        } else if (!nextPage.equals(other.nextPage))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Page [data=" + data + ", nextPage=" + nextPage + "]";
    }
    
    
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值