title: Adding a Node in a Singly linked lists (supports adding in front, end and middle)
body: <p>I am trying to write an "add" function that takes in the value held in the node (denoted 'n'), and the position the node is to be added into the linkedlist (denoted 'pos'). </p>
  
  <p>I have seen code where there are 3 separate add functions - addAtBeginning, addAtMiddle, addAtEnd, but I want one add function that does all of these. </p>
  
  <p>I have written code for the add(int n, int pos), but it is not giving me my expected output. </p>
  
  <p>For instance, in my main, i have:</p>
  
  <pre><code>LinkedList num;
  num.add(5,1);
  
  
  num.add(6,2);
  
  num.add(7,2);
  num.printList();
  </code></pre>
  
  <p>And I am expecting output: 5 7 6, (as the 7 will get shifted into the second position, and the 6 will then shift to the third position), except I am getting output: 5 6 7, where the 7 is added to the 3rd position. </p>
  
  <p>Also, I have already written my Node class and LinkedList class. I have been testing my functions in these classes in small increments, and everything else seems to be fine except for my add function.</p>
  
  <pre><code>Node * newNode = new Node();
  
  newNode-&gt;setValue(n); //Node gets value n
  
  int i=1; //ie. first position is 1, not 0
  
  Node * current = head;
  
  if (current == nullptr) //ie. then new node IS the head
  {
      head = newNode;
      head-&gt;next=nullptr;
      return;
  }
  
  if (current-&gt;next==nullptr) //adding to end of list
  {
  
      current-&gt;next = newNode;
      newNode-&gt;next = nullptr;
  
  }
  else //if inserting Node at middle, (neither at beginning or end)
  {
  
  
      while ( i&lt;pos &amp;&amp; current-&gt;next != nullptr) //traverse thru list
      {
          current=current-&gt;next;
          i = i+1;
      }
  
      Node * oldNext = current-&gt;next; 
  
      current -&gt; next = newNode;
  
      newNode -&gt; next = oldNext;
  
  
  
  }
  </code></pre>
  
  <p>There are no error messages when I compile.</p>