The linked list can be a single-chain table or a double-chain table. The subsequent node of the End Node of the linked list points to the header node and becomes a circular linked list.
Here we inherit double-stranded tables to implement a circular linked list. when the end of the double-stranded table is reached, let the cursor point to 0th nodes. When it reaches the beginning of the double-stranded table, let the cursor point to the end node, in this way, the circular double-stranded table is implemented. At the end, we use a classic Joseph question as an example of circular linked list.
1. Circular linked listCode:
/*
* File: circularly1_list. CS
* Author: Zhenxing Zhou
* Date: 2008-12-07
* Blog: Http://www.xianfen.net/
*/
Using System;
Namespace Xianfen. net. Datastructure
{
Public Class Circularly1_list < T > : Doublelinkedlist < T >
{
Private Doublelinkedlistnode < T > M_currentnode;
Private Int M_currentindex;
Public int currentindex
{< br> Get { return m_currentindex ;}
}
Public circularly1_list ()
: base ()
{< br> m_currentnode = m_head.next;
m_currentindex = 0 ;
}
Public circularly1_list (t)
: base (t)
{< br> m_currentnode = m_head.next;
m_currentindex = 0 ;
}
Public T getcurrent ()
{< br> If (m_count = 0 )
{< br> throw New indexoutofrangeexception ();
}
return m_currentnode.value;
}
Public T getnext ()
{< br> If (m_count = 0 )
{< br> throw New indexoutofrangeexception ();
}
If (m_currentnode ! = null )
{< br> m_currentnode = m_currentnode.next;
m_currentindex ++ ;< BR >}
If (m_currentnode = null )
{< br> m_currentnode = m_head.next;
m_currentindex = 0 ;
}
return m_currentnode.value;
}
Public T getprevious ()
{< br> If (m_count = 0 )
{< br> throw New indexoutofrangeexception ();
}
If(M_currentnode! = Null)
{
M_currentnode=M_currentnode.prior;
M_currentindex--;
}
If (M_currentnode = Null | M_currentnode = M_head)
{
M_currentnode = M_tail;
M_currentindex = M_count - 1 ;
}
ReturnM_currentnode.value;
}
}
}
2. Solve Joseph's problem with a circular linked list
Problem description: N people are circled and reported from 1 to m people, and then the next person continues to report from 1 to m people, until only one person is left. Show the last person left.
Code: Const Int M = 9 ;
Const Int N = 7 ;
Circularly1_list < Int > List = New Circularly1_list < Int > ();
//Filling cyclic linked list
For(IntI= 1; I<M; I++)
{
List. Add (I );
}
IntTempcounter= 0;
While (List. Count > 1 )
{
Tempcounter ++ ;
List. getprevious ();
// Select the middle out of the column
If (Tempcounter = N)
{
Tempcounter = 0 ;
Console. writeline (list. getcurrent () + " Column! " );
List. removeat (list. currentindex );
}
}
Console. writeline (list. getnext ()+ "Left");
Running result: 2 columns!
3 columns!
1 column!
7 columns!
4 columns!
8 columns!
6 columns!
5 left
If you change the statement highlighted above to: List. getnext ();
The running result is changed to: 7!
6 columns!
8 columns!
2 columns!
5 columns!
1 column!
3 columns!
4 left