java使用鏈表實現(xiàn)約瑟夫環(huán)
更新時間:2019年05月06日 11:12:23 作者:hairongtian
這篇文章主要為大家詳細介紹了java使用鏈表實現(xiàn)約瑟夫環(huán),具有一定的參考價值,感興趣的小伙伴們可以參考一下
約瑟夫環(huán)是一個數(shù)學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數(shù),數(shù)到m的那個人出列;他的下一個人又從1開始報數(shù),數(shù)到m的那個人又出列;依此規(guī)律重復下去,直到圓桌周圍的人全部出列。求出出隊序列。
采用鏈表實現(xiàn),結(jié)點數(shù)據(jù)就是編號。
package com.dm.test;
public class Test2
{
public static void main(String[] args)
{
//頭結(jié)點
Node root = new Node(1);
int[] order = build(root,9,5);
for(int i =0;i<order.length;i++)
{
System.out.print(order[i]+" ");
}
}
//將約瑟夫環(huán)建成一個鏈表
public static int[] build(Node root,int n, int m)
{
Node current = root;
for(int i = 2; i<=n; i++)
{
Node node = new Node(i);
current.next = node;
current = node;
}
current.next = root;
int[] order = come(root,n,m);
return order;
}
//出隊列
//結(jié)束條件:只有一個結(jié)點時,這個結(jié)點的next是它自身
//將出來的數(shù),放在一個數(shù)組中,遍歷數(shù)組就是出隊序列
public static int[] come(Node root,int n, int m)
{
int[] order = new int[n];
int j = 0;
Node p = root;
while(p.next!=p)
{
int i = 1;
while(i<m-1)
{
p=p.next;
i++;
}
if(i==m-1)
{
order[j]=p.next.data;
j++;
p.next = p.next.next;
p=p.next;
}
}
order[j]=p.data;
return order;
}
}
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
next= null;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java的JSON格式轉(zhuǎn)換庫GSON的初步使用筆記
GSON是Google開發(fā)并在在GitHub上開源的Java對象與JSON互轉(zhuǎn)功能類庫,在Android開發(fā)者中也大受歡迎,這里我們就來看一下Java的JSON格式轉(zhuǎn)換庫GSON的初步使用筆記:2016-06-06
Java常用正則表達式驗證工具類RegexUtils.java
相信大家對正則表達式一定都有所了解和研究,這篇文章主要為大家分享了Java 表單注冊常用正則表達式驗證工具類,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
詳解SpringCloud Gateway之過濾器GatewayFilter
這篇文章主要介紹了詳解SpringCloud Gateway之過濾器GatewayFilter,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
SpringSecurity實現(xiàn)多種身份驗證方式
本文主要介紹了SpringSecurity實現(xiàn)多種身份驗證方式,包括表單的認證、HTTP基本認證、HTTP摘要認證、證書認證、OpenIDConnect或OAuth2.0的認證、記住我功能和LDAP認證,感興趣的可以了解一下2025-03-03

