creating a linked list in c# code example
Example 1: create and return linked list c#
public class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
}
}
class Program
{
private static void Main(string[] args)
{
Node head = new Node(4);
Node nodeB = new Node(2);
Node nodeC = new Node(3);
Node nodeD = new Node(10);
head.next = nodeB;
nodeB.next = nodeC;
nodeC.next = nodeD;
Console.WriteLine(countNodes(head));
}
static int countNodes(Node head)
{
int count = 1;
Node current = head;
while (current.next != null)
{
current = current.next;
count += 1;
}
return count;
}
Example 2: c# singly linked list
public class LinkedList
{
public class Node
{
public Node next = null;
public object data;
}
private Node root = null;
public Node First { get { return root; } }
public Node Last
{
get
{
Node curr = root;
if (curr == null)
return null;
while (curr.next != null)
curr = curr.next;
return curr;
}
}
}