雙向鏈表是一種鏈表結構,每個節(jié)點包含兩個指針,一個指向前一個節(jié)點,一個指向后一個節(jié)點。雙向鏈表的查找算法可以根據需求進行不同的實現(xiàn),以下是一個簡單的雙向鏈表查找算法示例:
using System;
class Node
{
public int data;
public Node prev;
public Node next;
public Node(int data)
{
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList
{
private Node head;
public DoublyLinkedList()
{
this.head = null;
}
public void AddNode(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = newNode;
newNode.prev = current;
}
}
public Node FindNode(int data)
{
Node current = head;
while (current != null && current.data != data)
{
current = current.next;
}
return current;
}
public void PrintList()
{
Node current = head;
while (current != null)
{
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
}
class Program
{
static void Main()
{
DoublyLinkedList list = new DoublyLinkedList();
list.AddNode(1);
list.AddNode(2);
list.AddNode(3);
list.AddNode(4);
list.PrintList();
Node node = list.FindNode(3);
if (node != null)
{
Console.WriteLine("Node found: " + node.data);
}
else
{
Console.WriteLine("Node not found");
}
}
}
在上面的示例中,定義了一個Node
類表示雙向鏈表的節(jié)點,包含數(shù)據和指向前一個節(jié)點和后一個節(jié)點的指針。然后定義了DoublyLinkedList
類來管理雙向鏈表,包括添加節(jié)點、查找節(jié)點和打印鏈表等方法。最后在Main
方法中進行了簡單的測試。