private class ListNode { public int Data = 0; public ListNode Next = null; public ListNode(int data, ListNode next) { Data = data; Next = next; } } private ListNode Head = null; private ListNode Tail = null; public void Print() { ListNode p = Head; while (p != null) { Console.WriteLine(p.Data); p = p.Next; } } 

Do I understand correctly that in the Print method, "p" is a local reference variable that refers to the main element of the list? (exactly in the first line of the method)

  • Yes. "main" - in the sense, the first - Igor
  • In this case, as in the 3rd line of the same method, you can return a Data variable of type int, because "p" is a local variable of reference type only, i.e. for links? - Martin Eden
  • @MartinEden in the 3rd line you refer to the p object and its Data field. - Exodium
  • But this link points to a ListNode object, which has Data - Igor
  • one
    but not at the same time :) - Igor

1 answer 1

The ListNode class has a field for storing data and a link to the next element of the same type. In the Print method, nothing happens as a list traversal: a reference to the head of the list is written to the local variable p, then the data of the current element is output to the console in a loop, and the pointer to the next element of the list is assigned to the variable p. The operation is repeated until the elements run out.

If an element is present twice in the list, the cycle will never end - the program will run endlessly in a circle. To avoid this, you should somehow mark the visited nodes: either by adding the Visited property to the ListNode, or by adding each visited item to a separate collection (HashSet). When the vertex re-occurs, the cycle is interrupted.