How to convert a number to a linked list in C++ : <p>I am starting out learning about linked lists and am trying to solve a programming problem. The output needs to be a number represented as a linked list. For example, if the number is 123, the linked list needs to be 3->2->1.  </p>

<p>According to my implementation, I am doing all other functions beforehand and have the final output number as an int, and need to convert it to a linked list. I tried the following code.</p>

<pre><code>    ListNode* numToLL(int sum){

         ListNode* mainHead;
         int remainder = sum % 10;
         mainHead-&gt;val = remainder;
         sum = sum / 10;
         ListNode* head;
         head = mainHead;
         while (sum != 0){
             ListNode* nextNode;
             int remainder = sum % 10;            
             nextNode-&gt;val = remainder;
             head-&gt;next = nextNode;
             head = nextNode;
             sum = sum / 10;
         }
         return mainHead;
    }
</code></pre>

<p>I know this is incorrect, but I am not sure how to correct it. The error message for this says:  "runtime error: member access within null pointer of type 'struct ListNode'" on the 3rd line inside the function.</p>
