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
}
}
Value) 和指向下一个节点的引用 (Next)。AddLast 方法用于在链表末尾添加一个新节点。PrintList 方法用于遍历并打印链表中的所有节点值。通过这段代码,你可以了解如何在 C# 中实现一个简单的单向链表。
上一篇:c#foreach
下一篇:c# string format
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站