在C#中實現雙向鏈表的異常處理可以通過使用try-catch塊來捕獲異常。以下是一個簡單的示例:
using System;
public class Node<T>
{
public T Data { get; set; }
public Node<T> Next { get; set; }
public Node<T> Prev { get; set; }
public Node(T data)
{
Data = data;
}
}
public class DoublyLinkedList<T>
{
private Node<T> head;
private Node<T> tail;
public void Add(T data)
{
Node<T> newNode = new Node<T>(data);
if (head == null)
{
head = newNode;
tail = newNode;
}
else
{
tail.Next = newNode;
newNode.Prev = tail;
tail = newNode;
}
}
public void Print()
{
Node<T> current = head;
while (current != null)
{
Console.Write(current.Data + " ");
current = current.Next;
}
Console.WriteLine();
}
}
class Program
{
static void Main()
{
try
{
DoublyLinkedList<int> list = new DoublyLinkedList<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Print();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
在上面的示例中,我們將異常處理放在了Main方法中。當在添加節點時發生異常時,將捕獲并打印出錯誤消息。您可以根據自己的需求添加更多的異常處理邏輯。