C#双向链表的异常处理

   2024-10-01 4350
核心提示:在C#中实现双向链表的异常处理可以通过使用try-catch块来捕获异常。以下是一个简单的示例:using System;public class NodeT{pub

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号