I am trying to delete a Node from a linked list. Below is the code I have tried.
public class Node : IDisposable
{
public int Value { get; set; }
public Node Next { get; set; }
public Node(int value)
{
this.Value = value;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Next.Dispose();
}
}
}
public class LinkedList
{
Node head;
public void CreateList()
{
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
head = node1;
node1.Next = node2;
node2.Next = node3;
}
public void DeleteLastItem()
{
Node prevNode = head;
Node nextNode = head;
while (nextNode.Next != null)
{
prevNode = nextNode;
nextNode = nextNode.Next;
}
prevNode.Next = null;
nextNode.Dispose();
}
}
I wanted to dispose the nextNode
(which is nothing but the last node. And it will not be part of the Linked List).
When I try above code, I am getting below exception:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
How can I proceed here ? How can I dispose a Node
object?