C#雙向鏈表的異常處理

c#
小樊
82
2024-08-23 15:46:31

在C#中實(shí)現(xiàn)雙向鏈表的異常處理可以通過(guò)使用try-catch塊來(lái)捕獲異常。以下是一個(gè)簡(jiǎn)單的示例:

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方法中。當(dāng)在添加節(jié)點(diǎn)時(shí)發(fā)生異常時(shí),將捕獲并打印出錯(cuò)誤消息。您可以根據(jù)自己的需求添加更多的異常處理邏輯。

0