title: Inserting at the end with C++
body: <p>I wrote code that can create a Linked List, insert elements into the beginning or end, and then display it. </p>
  
  <pre><code>struct ListElem
  {
      int        info;
      ListElem * next;
  };
  
  // shortcut for list = pointer to a list element
  typedef ListElem * List;
  
  // empty list is a Null Pointer
  const List emptyList = 0;
  
  void printList(List lst) {
          for (; lst!= 0; lst = lst-&gt;next) {
              cout &lt;&lt; lst-&gt;info &lt;&lt; endl;
          }
  }
  void insertElem(List&amp; lst, int info) {
      ListElem *ptrElem = new ListElem;
      ptrElem-&gt;info = info;
      ptrElem-&gt;next = lst;
      lst = ptrElem;
  }
  void insertLast(List&amp; lst, int info) {
      ListElem *ptrElem = new ListElem;
      ptrElem-&gt;info = info;
      ptrElem-&gt;next = NULL;
      if (lst == emptyList) {
          insertElem(lst, info);
          return;
      }
      else {
          while (lst -&gt;next) {
              lst = lst-&gt;next;
          }
          lst-&gt;next = ptrElem;
      }
  }
  </code></pre>
  
  <p>I tried out the insertLast function on main: </p>
  
  <pre><code>int main()
  {
      // fill List with values 1 to 10
      List list1 = emptyList;
      for (int value = 1; value &lt;= 10; value++)
      {
          //insertElem( list1, value ); 
          insertLast(list1, value);
      }
  
      //print list
      printList(list1);  // should provide sequence 1 2 3 ... 10 
  </code></pre>
  
  <p>But for some reason printList only shows 9 and 10, instead of 1,2,3,..,10. This problem only happens with insertLast. insertElem seems to work fine. </p>