Use the C # circular linked list to solve the problem of Joseph's ring

Source: Internet
Author: User
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 ;
}
}
}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.