I am trying to create a linked list just to see if I can, and I am having trouble getting my head around it. Does anyone have an example of a very simple implementation of Linked list using C#? All the examples I have found so far are quite overdone.
A singly linked list is a type of linked list that is unidirectional, that is, it can be traversed in only one direction from head to the last node (tail). Each element in a linked list is called a node. A single node contains data and a pointer to the next node which helps in maintaining the structure of the list.
The function insert() inserts the data into the beginning of the linked list. It creates a new_node and inserts the number in the data field of the new_node. Then the new_node points to the head. Finally the head is the new_node i.e. the linked list starts from there.
A Linked List, at its core is a bunch of Nodes linked together.
So, you need to start with a simple Node class:
public class Node { public Node next; public Object data; }
Then your linked list will have as a member one node representing the head (start) of the list:
public class LinkedList { private Node head; }
Then you need to add functionality to the list by adding methods. They usually involve some sort of traversal along all of the nodes.
public void printAllNodes() { Node current = head; while (current != null) { Console.WriteLine(current.data); current = current.next; } }
Also, inserting new data is another common operation:
public void Add(Object data) { Node toAdd = new Node(); toAdd.data = data; Node current = head; // traverse all nodes (see the print all nodes method for an example) current.next = toAdd; }
This should provide a good starting point.
Based on what @jjnguy said, here's the full Console App example:
public class Node { public Node next; public Object data; } public class LinkedList { private Node head; public void printAllNodes() { Node current = head; while (current != null) { Console.WriteLine(current.data); current = current.next; } } public void AddFirst(Object data) { Node toAdd = new Node(); toAdd.data = data; toAdd.next = head; head = toAdd; } public void AddLast(Object data) { if (head == null) { head = new Node(); head.data = data; head.next = null; } else { Node toAdd = new Node(); toAdd.data = data; Node current = head; while (current.next != null) { current = current.next; } current.next = toAdd; } } } class Program { static void Main(string[] args) { Console.WriteLine("Add First:"); LinkedList myList1 = new LinkedList(); myList1.AddFirst("Hello"); myList1.AddFirst("Magical"); myList1.AddFirst("World"); myList1.printAllNodes(); Console.WriteLine(); Console.WriteLine("Add Last:"); LinkedList myList2 = new LinkedList(); myList2.AddLast("Hello"); myList2.AddLast("Magical"); myList2.AddLast("World"); myList2.printAllNodes(); Console.ReadLine(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With