I’m learning how to make a linked list in c#. I have the below code which is not working for me. I just want to add the nodes in the main as i have below then iterate over all nodes that will print to the console.
using System;
class node
{
public object data;
public node next;
public node()
{
data = null;
next = null;
}
public node(object o)
{
data = o;
next = null;
}
public node(object data, node next)
{
this.data = data;
this.next = next;
}
}
class linkedList
{
private node headNode;
private node tailNode;
int node_count;
public void add(object entry)
{
if (headNode == null)
{
node newNode = new node(entry);
headNode = newNode;
++node_count;
}
else
{
if (node_count == 1)
{
node newNode = new node(entry, headNode);
tailNode = newNode;
}
else
{
node newNode = new node(entry, tailNode);
tailNode = newNode;
}
++node_count;
}
}
public void returnData()
{
if (headNode.next != null)
{
while (headNode.next != null)
{
Console.WriteLine(headNode.data + "\n");
}
}
else
Console.WriteLine("Not Available");
}
}
class Exercise
{
static int Main()
{
linkedList ll = new linkedList();
ll.add(8);
ll.add(2);
ll.add(7);
ll.add(4);
ll.add(9);
ll.add(10);
ll.returnData();
Console.ReadLine();
return 0;
}
}
Your code is completely broken.
Here’s minimal changes needed to run it