温馨提示×

C#双向链表的异常处理

c#
小樊
82
2024-08-23 15:46:31
栏目: 编程语言

在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方法中。当在添加节点时发生异常时,将捕获并打印出错误消息。您可以根据自己的需求添加更多的异常处理逻辑。

0