Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 链表

作者:月下孤魂   发布日期:2025-12-03   浏览:81

using System;
using System.Collections.Generic;

// 定义链表节点类
public class ListNode
{
    public int Value { get; set; }
    public ListNode Next { get; set; }

    public ListNode(int value)
    {
        Value = value;
        Next = null;
    }
}

// 定义链表类
public class LinkedList
{
    private ListNode head;

    public LinkedList()
    {
        head = null;
    }

    // 添加节点到链表末尾
    public void AddLast(int value)
    {
        ListNode newNode = new ListNode(value);
        if (head == null)
        {
            head = newNode;
        }
        else
        {
            ListNode current = head;
            while (current.Next != null)
            {
                current = current.Next;
            }
            current.Next = newNode;
        }
    }

    // 打印链表内容
    public void PrintList()
    {
        ListNode current = head;
        while (current != null)
        {
            Console.Write(current.Value + " ");
            current = current.Next;
        }
        Console.WriteLine();
    }
}

// 测试代码
class Program
{
    static void Main(string[] args)
    {
        LinkedList list = new LinkedList();
        list.AddLast(1);
        list.AddLast(2);
        list.AddLast(3);

        list.PrintList();  // 输出: 1 2 3
    }
}

解释说明:

  1. ListNode 类:表示链表中的一个节点,包含一个整数值 (Value) 和指向下一个节点的引用 (Next)。
  2. LinkedList 类:表示整个链表,包含添加节点和打印链表的方法。
    • AddLast 方法用于在链表末尾添加一个新节点。
    • PrintList 方法用于遍历并打印链表中的所有节点值。
  3. 测试代码:创建一个链表实例,并向其中添加几个节点,最后打印链表内容。

通过这段代码,你可以了解如何在 C# 中实现一个简单的单向链表。

上一篇:c#foreach

下一篇:c# string format

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站