A few days ago, I saw an interview question about Joseph's ring. So I tried to do it first. I didn't use the sort list class of the. NET class library. I implemented a loop linked list structure and then simulated the game process to get the result.
DetailsCodeAs follows:
Code Class Program
{
Static Void Main ( String [] ARGs)
{
Const Int Human_max = 17 ;
Const Int Human_index = 3 ;
Const Int Human_number = 0 ;
Linktable < Human > List = New Linktable < Human > ();
For ( Int I = 0 ; I < Human_max; I ++ )
{
List. Add ( New Human (I ));
}
Human human = List. first;
Int Number = Human_number;
Do
{
If (Number = Human_index)
{
Number = 0 ;
Console. writeline (human. ID );
List. Remove (human );
}
Else
{
Number ++ ;
Human = (Human) Human. Next;
}
}
While (Human. Next ! = Human );
Console. writeline (human. ID );
Console. Read ();
}
Public Class Human: linktablenode {
Public Human ( Int ID ){
This . ID = ID;
}
Public Int Id { Get ; Set ;}
}
/// <Summary>
/// Round chain table
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
Public Class Linktable < T > Where T: linktablenode
{
Public List < T > List = New List < T > ();
Public T first
{
Get
{
Return List. Count > 0 ? List [ 0 ]: Default (T );
}
}
Public Void Add (T)
{
T. Previous = List. Count = 0 ? T: list [list. Count - 1 ];
T. Next = List. Count = 0 ? T: list [ 0 ];
If (List. Count > 0 )
{
List [ 0 ]. Previous = T;
T. Previous. Next = T;
}
List. Add (t );
}
Public Void Remove (T)
{
Int I = List. indexof (t );
If (List. Count = 1 )
{
List. Remove (t );
}
Else
{
T. Previous. Next = T. Next;
T. Next. Previous = T. Previous;
}
}
}
/// <Summary>
/// Linked List Node
/// </Summary>
Public Class Linktablenode
{
/// <Summary>
/// Next Node
/// </Summary>
Public Linktablenode next
{
Get ;
Set ;
}
/// <Summary>
/// Previous Node
/// </Summary>
Public Linktablenode previous
{
Get ;
Set ;
}
}
}