How to iterate through Linked List

前端 未结 4 1462
挽巷
挽巷 2021-01-12 08:12

I have looked around and I can\'t really find an answer I can understand or it doesn\'t apply to me. I have this class:

class Node
{
    public int value;
           


        
4条回答
  •  -上瘾入骨i
    2021-01-12 08:51

    For this kind of list, you usually keep a reference to the current node (which starts with the head), and after each iteration, you change the value of that reference to the next node. When currentNode becomes null, you have reached the end of the list, as the last element doesn't have a next element.

    Something like this:

    Node currentNode = head;
    while (currentNode != null) {
        // do stuff with currentNode.value
        currentNode = currentNode.Next;
    }
    

    By the way, the BCL already contains some useful classes for this sort of task:

    • List, which internally uses arrays to store elements and provides random access to them
    • LinkedList, which uses the same principle as your custom class.

    But maybe you need to do it the way you do for some reason :)

提交回复
热议问题