在C#中,双向链表的节点查找可以通过以下几种方法实现:
public Node FindNode(int value)
{
Node current = head;
while (current != null)
{
if (current.Value == value)
{
return current;
}
current = current.Next;
}
return null;
}
public Node FindNodeFromEnd(int value)
{
Node current = tail;
while (current != null)
{
if (current.Value == value)
{
return current;
}
current = current.Previous;
}
return null;
}
public class DoublyLinkedList
{
private Node head;
private Node tail;
private Dictionary<int, Node> nodeLookup = new Dictionary<int, Node>();
public void AddNode(int value)
{
Node newNode = new Node(value);
if (head == null)
{
head = newNode;
tail = newNode;
}
else
{
tail.Next = newNode;
newNode.Previous = tail;
tail = newNode;
}
nodeLookup[value] = newNode;
}
public Node FindNode(int value)
{
if (nodeLookup.ContainsKey(value))
{
return nodeLookup[value];
}
return null;
}
}
这些方法都可以用于在双向链表中查找节点。从头节点或尾节点开始遍历的方法需要遍历整个链表,时间复杂度为O(n)。使用哈希表存储节点的方法可以在O(1)时间内查找节点,但需要额外的空间来存储哈希表。根据实际需求和性能考虑,可以选择合适的查找方法。