I get an error

Object reference does not indicate an object instance.

in the Add() method of the SortedLinkedList class. I want to compare an element of any type with another element of the same type, it is assumed that the types will be either an int, a double, or a string. I had to use the CompareTo() method instead of the < operator < Tell me how in my case you can compare the data of two nodes without any errors, taking into account that they are of the same type. If you use the CompareTo() method, then tell me how to do it without errors.

 public class Node<D> { public D Data { get; set; } public Node(D data) { Data = data; } public Node<D> Next { get; set; } } public class SortedLinkedList<D> where D: IComparable { Node<D> head; // first element Node<D> tail; // last element int count = 0; public int Count {get { return count; } set { count = value; } } public bool IsEmpty() { return count == 0; } public void PrintList() { Node<D> current = head; string result = ""; while (current != null) { result += current.Data; result += ", "; current = current.Next; } Console.WriteLine(result); } public void Add(D Data) { Node<D> node = new Node<D>(Data); if (head == null) // if the list is empty { head = node; // then we're about to fill the first slot. } else { Node<D> current = head; Node<D> previous = null; while (current.Data.CompareTo(node.Data) < 0) { previous = current; current = current.Next; } previous.Next = node; node.Next = current; } count++; } class Program { static void Main(string[] args) { SortedLinkedList<int> A = new SortedLinkedList<int>(); int[] s = { 1, 2, 3, 4, 5, 7, 8, 9 }; for (int i = 0; i < s.Length; i++) { A.Add(s[i]); } A.PrintList(); Console.ReadKey(); } } 
  • You need to add a check for null in the while loop: current == null || current.Data... current == null || current.Data... The output of this check will occur if the added element is the last one. - Vlad
  • on which line throws an exception? I mean that on the previous.Next ? - Vardan Vardanyan

1 answer 1

 while (current.Data.CompareTo(node.Data) < 0) { previous = current; current = current.Next; } 

In this loop, your current may become equal to null (if you add a value to the end of the list, that is, add the most “big” element compared to those already in the list) and you will get this error. Therefore, you should add an additional check on null for current

 while (current != null && current.Data.CompareTo(node.Data) < 0) { previous = current; current = current.Next; }