在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)時間內查找節點,但需要額外的空間來存儲哈希表。根據實際需求和性能考慮,可以選擇合適的查找方法。