數據結構與算法-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 + "]";
    }
    
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章