I used the C # language to create a single-cycle linked list for my training assignment a few days ago. I have learned this before when talking about the data structure, but at that time I used C, the pointer is used, but the pointer is not in C #. How can I create a single-loop linked list in C? In fact, when creating a new object, we can understand it as a pointer. in C #, it doesn't mean that we can't use a pointer, but encapsulate it, it is invisible to users. Next, we use the single-loop linked list implemented by C.
First of all, define a struct. in C #, It is a class. The Code is as follows:
Class CircleSingleNode <T>
{
Public T Data;
Public CircleSingleNode <T> nodeNext;
Public CircleSingleNode (){}
Public CircleSingleNode (T data) {Data = data ;}
}
By the way, our manager asked me to write with generics. After all, we should try our best to apply what we have learned.
After a struct is defined, we need to define a method for adding nodes. If the single-loop linked list has only one back node without the front node, then the back node of the last node points to the first node, this forms a loop. I have defined a header node to store the first node. The Code is as follows:
Class CircleSingleTable <T>
{
Public int count {get; set ;}
CircleSingleNode <T> header;
CircleSingleNode <T> current;
Public CircleSingleTable (T data)
{
Header = new CircleSingleNode <T> (data );
Current = header;
}
Public void AddLastNode (T data)
{
CircleSingleNode <T> newNode = new CircleSingleNode <T> (data );
Current. nodeNext = newNode;
NewNode. nodeNext = header;
Current = newNode;
Count ++;
}
Public void showMessage (int count)
{
For (int I = 0; I <count; I ++)
{
Header = header. nodeNext;
Console. WriteLine (header. Data. ToString ());
}
}
}
However, after writing this code, a small error occurs. For example, I add the 10 numbers 0-9 in a loop to the linked list, and then print the result as 0012345678900123456789 .... in this way, I feel that the value of nodeNext is not assigned to the first node, so that the next node of this header node points to the value of this header node and then points to 1 2 3... I don't know how to solve this problem. Please give me some comments. Thank you...