如何遍历链接列表 [英] How to iterate through Linked List
问题描述
我环顾四周,我找不到真正可以理解的答案,或者它不适用于我.我有这个课:
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;
public Node next;
}
我有一个名为 head
的成员变量,它是单个链接列表的头部.现在,我尝试遍历链接列表的不同节点以搜索特定的 value
.我知道如果我手动进行操作,那么如果我想要第5个节点的 value
,那么我会执行 head.next.next.next.next.value
.对于一个非常大的链表,这将很快变得乏味,所以我的问题是如何创建一个循环来迭代此循环,以便可以检查节点的每个节点中的 value
变量.链表?
And I have a member variable called head
which is the head of the single linked list. Now I am trying to iterate through the different nodes of the linked list to search for a specific value
. I know if I do it manually then I would do head.next.next.next.next.value
if I want the value
of the 5th node. This would quickly get tedious for a linked list of very large size so my question is how can I create some loop to iterate through this so that I can check the value
variable in each node of the linked list?
推荐答案
您可以按照以下步骤遍历您的课程:
You iterate through your class as follows:
var currentNode = head;
while ((currentNode != null) && (currentNode.Value != desiredValue))
currentNode = currentNode.next;
当 while
循环完成时,currentNode将为 null
或包含具有所需值的节点.
When the while
loop completes, currentNode will be null
or contain a node with the desired value.
这篇关于如何遍历链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!