C# リスト作成の基本:初心者向け徹底ガイド
C#でリンクリストを作成する方法は2つあります。
- クラス:これは、C#に組み込まれたリストの実装です。直接使用することができます。最初にSystem.Collections.Generic名前空間をインポートする必要があります。そして、以下のコードを使用してリストを作成することができます。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
LinkedList<int> linkedList = new LinkedList<int>();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
foreach (var item in linkedList)
{
Console.WriteLine(item);
}
}
}
- 自作のリンクリストクラス:リンクリストの機能を実装するために、自作のリンクリストクラスを作成することもできます。たとえば、NodeクラスとLinkedListクラスを作成して、リンクリストのノードとリンクリスト自体を表すことができます。
using System;
class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
class LinkedList
{
public Node head;
public void Add(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = newNode;
}
}
public void Display()
{
Node current = head;
while (current != null)
{
Console.WriteLine(current.data);
current = current.next;
}
}
}
class Program
{
static void Main()
{
LinkedList linkedList = new LinkedList();
linkedList.Add(1);
linkedList.Add(2);
linkedList.Add(3);
linkedList.Display();
}
}
どの方法を採用しても、ノードの追加や削除などの操作を行うことでリストを操作することができます。