While trying to understand how a singly list can be implemented in C#, I came across the link below :
Creating a very simple linked list.
However, as I am new to
There is an easy way to create the Singly Linked List. Lets try to understand the concept. If concept is clear then you can understand the logic itself. Singly Linked List has Node with two sections. One has data value in it and other has the reference address of next node. Take the look into following code:
First We need to create the Linked List Node Class
///
/// Creating the Real World Entity of Linked List Node
///
public class LinkedListNode
{
public Object Value { get; set; }
public LinkedListNode Next { get; set; }
}
Here the class has Value and Holder to hold the reference of next Node in the sequence. Next we need to create the Linked List itself
///
/// Creating the Linked List Class Itself. It defines the First and Last Nodes of Linked List
///
public class LinkedList
{
public LinkedListNode First { get; set; }
public LinkedListNode Last { get; set; }
///
/// Method to Add items into the Linked List
///
///
public void AddToLinkedList(object _value)
{
LinkedListNode node = new LinkedListNode();
node.Value = _value;
if (First == null)
{
First = node;
Last = node;
}
else
{
Last.Next = node;
Last = node;
}
}
///
/// Method to display all items. We can further implement the IEnumerable interface
/// to Yield IEnumerator Interface.
///
public void DisplayAllItems()
{
LinkedListNode current = First;
while (current != null)
{
Console.WriteLine(current.Value);
current = current.Next;
}
}
}
Here, the Key is to Add items in to the Linked List. First we need to check if the linked list does exist or not. We check the First or Head Node in the linked List. If it is empty we assign the node as first entry point. At this stage the Last item is the first item itself.
Now this is how we add and display items
class Program
{
static void Main(string[] args)
{
LinkedList singlyLinkedList = new LinkedList();
singlyLinkedList.AddToLinkedList(4);
singlyLinkedList.AddToLinkedList(5);
singlyLinkedList.AddToLinkedList(7);
singlyLinkedList.AddToLinkedList(2);
singlyLinkedList.AddToLinkedList(1);
singlyLinkedList.AddToLinkedList(10);
singlyLinkedList.DisplayAllItems();
Console.ReadLine();
}
}
Let me know if it makes sense :)