双向链表是一种链表结构,每个节点包含两个指针,一个指向前一个节点,一个指向后一个节点。双向链表的查找算法可以根据需求进行不同的实现,以下是一个简单的双向链表查找算法示例:
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
类表示双向链表的节点,包含数据和指向前一个节点和后一个节点的指针。然后定义了DoublyLinkedList
类来管理双向链表,包括添加节点、查找节点和打印链表等方法。最后在Main
方法中进行了简单的测试。