在C#中,雙向鏈表的節(jié)點查找可以通過以下幾種方法實現(xiàn):
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;
}
}
這些方法都可以用于在雙向鏈表中查找節(jié)點。從頭節(jié)點或尾節(jié)點開始遍歷的方法需要遍歷整個鏈表,時間復(fù)雜度為O(n)。使用哈希表存儲節(jié)點的方法可以在O(1)時間內(nèi)查找節(jié)點,但需要額外的空間來存儲哈希表。根據(jù)實際需求和性能考慮,可以選擇合適的查找方法。