title: C++ Linked list implementation crashing
body: <p>I am trying to implement a linked list for a data structures class and I am having some difficulty with the searching portion of the algorithm.</p>
  
  <p>Below is the offending code, which I have tried to implement following the pseudo-code in the MIT introduction to algorithms text:</p>
  
  <pre><code>//
  // Method searches and retrieves a specified node from the list
  //
  Node* List::getNode(unsigned position)
  {
      Node* current = m_listHead;
  
      for(unsigned i = m_listSize-1; (current != 0) &amp;&amp; (i != position); --i)
              current = current-&gt;next;
  
      return current;
  }
  </code></pre>
  
  <p>The head at this point in the program is the 4th node, which contains the value of int 5. the problem appears to be in the body of the for-loop, where the pointer to the node object is assigned to the next node. But this is going beyond the head of the node, so it is essentially pointing at some random location in memory (this makes sense). </p>
  
  <p>Shouldn't the algorithm be moving to the previous Node instead of the next Node in this case? Below is the pseudo-code:</p>
  
  <pre><code>LIST-SEARCH(L, k)
      x &lt;- head
      while x != NIL and key != k
          do x &lt;- next[x]
      return x
  </code></pre>
  
  <p>Also, here is the header file for my Linked list implementation. I haven't tried to implement it in Template form yet just to keep things simple:</p>
  
  <pre><code>#ifndef linkList_H
  #define linkList_h
  
  
  //
  // Create an object to represent a Node in the linked list object
  // (For now, the objects to be put in the list will be integers)
  //
  struct Node
  {
      // nodes of list will be integers
      int number;
      // pointer to the next node in the linked list
      Node* next;
  };
  
  
  //
  // Create an object to keep track of all parts in the list
  //
  class List
  {
  public:
  
      // Contstructor intializes all member data
      List() : m_listSize(0), m_listHead(0) {}
  
      // methods to return size of list and list head
      Node* getListHead() const { return m_listHead; }
      unsigned getListSize() const { return m_listSize; }
  
      // method for adding a new node to the linked list, 
      // retrieving and deleting a specified node in the list
      void addNode(Node* newNode);
      Node* getNode(unsigned position);
  
  private:
  
      // member data consists of an unsigned integer representing
      // the list size and a pointer to a Node object representing head
      Node* m_listHead;
      unsigned m_listSize;
  };
  
  #endif
  </code></pre>
  
  <p>Implementation of addNode method:</p>
  
  <pre><code>//
  // Method adds a new node to the linked list
  //
  void List::addNode(Node* newNode)
  {
      Node* theNode = new Node;
  
      theNode = newNode;
      theNode-&gt;next;
      m_listHead = theNode;
  
      ++m_listSize;
  }
  </code></pre>