采用循环双链表演示约瑟夫环代码:
由于是带空数据的头结点的循环双链表
所以在操作时显得复杂,仓促写的
package Cir_Double_list;
import javax.swing.plaf.TableHeaderUI;
import java.util.Arrays;
import java.util.Scanner;
public class my_Cir_double_list<T>
{
int length;
public DoubleNode<T> head;
public my_Cir_double_list()
{
this.head=new DoubleNode<T>();
length=0;
this.head.prev=this.head;
this.head.next=this.head;
}
public my_Cir_double_list(T[] values)
{
this();
this.length=values.length;
DoubleNode<T> rearnode=this.head;
for (T value : values)
{
rearnode.next = new DoubleNode<T>(value, rearnode, null);
rearnode = rearnode.next;
}
this.head.prev=rearnode;
rearnode.next=this.head;
}
@Override
public String toString()
{
String str = this.getClass().getName()+"(";
for (DoubleNode<T> p = this.head.next;p!=this.head; p=p.next)
// str += p.date.toString()+(p.next!=null?"," : "");
{
str += (p.date!=null ? p.date.toString() : "null")+(p.next!=null?"," : "null");//增加了输出时空数据的容错
// if (p.next==this.head)
}
return str+")";
}
public static my_Cir_double_list<Integer> outlist()
{
Integer [] x={1,2,3,4,5,6,7,8,9};
return new my_Cir_double_list<>(x);
}
public static void Josephus_show(int length,int distance)//约瑟夫环演示
{
distance--;
Integer[] jose = new Integer[length];
for (int x=0 ; x<length ; x++)
{
jose[x]=x+1;
}
System.out.println(Arrays.toString(jose));
my_Cir_double_list<Integer> linkedlist = new my_Cir_double_list<>(jose);
DoubleNode<Integer> start_node=linkedlist.head.next;
System.out.println("初始:"+linkedlist+"长度:"+linkedlist.length);
int falg = 0;
do
{
falg++;
for (int i = 0; i < distance; i++)
{
if (start_node.next == linkedlist.head)
start_node = linkedlist.head.next;
else
start_node = start_node.next;
}
//--------------------
if (start_node.next == linkedlist.head)
{
start_node = linkedlist.head.next;
linkedlist.head.prev = linkedlist.head.prev.prev;
linkedlist.head.prev.next = linkedlist.head;
linkedlist.length--;
} else if (start_node.prev == linkedlist.head)
{
start_node = start_node.next;
start_node.prev = linkedlist.head;
linkedlist.head.next = start_node;
linkedlist.length--;
} else
{
start_node = start_node.next;
start_node.prev.prev.next = start_node;
start_node.prev = start_node.prev.prev;
linkedlist.length--;
}
//----------------------
System.out.println("第" + falg + "次结果" + linkedlist);
try
{
Thread.sleep(100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
} while (linkedlist.length != 1);
}
public static void main(String[] args)
{
System.out.println("约瑟夫环演示:");
Josephus_show(41,3);
while (true)
{
System.out.print("请输入长度:(输入0结束)");
Scanner inlenth = new Scanner(System.in);
Scanner indistance = new Scanner(System.in);
int lenth,distance;
lenth= inlenth.nextInt();
if (lenth==0)
return;
System.out.print("请输入距离:");
distance = indistance.nextInt();
Josephus_show(lenth,distance);
}
}
}