I am creating linked list in c#, I have been using a website to learn from https://www.codeproject.com/Articles/1104980/Linked-List-Implementation-in-Csharp
This site has code that i try and I have issues with a problem. The code i am using is
public class Node
{
public Node Next;
public object Value;
}
public class LinkedList
{
private Node head;
private Node current;//This will have latest node
public int Count;
}
public LinkedList()
{
head = new Node();
current = head;
}
public void AddAtLast(object data)
{
Node newNode = new Node();
newNode.Value = data;
current.Next = newNode;
current = newNode;
Count++;
}
public void AddAtStart(object data)
{
Node newNode = new Node() { Value = data};
newNode.Next = head.Next;//new node will have reference of head's next reference
head.Next = newNode;//and now head will refer to new node
Count++;
}
The code copied from website, so should be no error. But my problem is, when i add items to the start of the list with AddAtStart and then i add at end of list with AddAtLast, AddAtLast deletes all the nodes i had added before and only now stores the new AddAtLast entry. I maby think this could be because of current. I think that current is thinking it is the head and not the last node, so when i add at end it adds at start and removes all. Could this be the cause of my problems.
If I only use AddAtStart it all works good, all nodes get added, i can have many nodes, but just when AddAtLast is used, everything goes away
EDIT i forgot my code was differet from site my apologies. I shall edit with my code I am using
public class LinkedList
{
private Node head;
private Node current;//This will have latest node
public int Count;
public LinkedList()
{
head = new Node();
current = head;
}
public void PrintAllNodes()
{
//Traverse from head
Console.Write("Head ->");
Node curr = head;
while (curr.Next != null)
{
curr = curr.Next;
Console.Write(curr.Value);
Console.Write("->");
}
Console.Write("NULL");
}
public void AddAtStart(object data)
{
Node newNode = new Node() { Value = data};
newNode.Next = head.Next;//new node will have reference of head's next reference
head.Next = newNode;//and now head will refer to new node
Count++;
}
public void AddAtLast(object data)
{
Node newNode = new Node();
newNode.Value = data;
current.Next = newNode;
current = newNode;
Count++;
}
}
LinkedListclass as well as theAddAtLast()andAddAtStart()methods are meant to be in theLinkedListclass?