title: Deleting the nth node in a linked list, can't delete first node?
body: <p>Below is a function that is designed to delete the nth node in a linked list. For example if I called <code>deleteN(head, 2)</code> it would delete the 2nd node in the list.</p>
  
  <pre><code>node *deleteN(node *head, int n)
  {
  
      if (head == NULL)
          return NULL;
  
  
      if (n == 1)
      {
          node *temp = head;
          //printf("the element is %d\n", temp-&gt;data);
          head = temp-&gt;next;
          free(temp);
          return head;
      }
  
      head-&gt;next = deleteN(head-&gt;next, n-1);
  
      return head;
  
  }
  </code></pre>
  
  <p>It works fine unless you call e.g. <code>deleteN(head, 1)</code>, which is supposed to delete the first node in the list, but when I call another function to print the list, it prints random addresses instead.</p>
  
  <p>Examples of what is happening in a list of <strong>4 nodes</strong> that contain the integer values <strong>23</strong>, <strong>24</strong>, <strong>25</strong>, and <strong>26</strong> in order (what is called in main then output):</p>
  
  <p><strong>Test case 1 (PASS):</strong></p>
  
  <p><code>deleteN(head, 2);</code></p>
  
  <p><code>printList(head);</code></p>
  
  <p><strong>Output:</strong></p>
  
  <p>23</p>
  
  <p>25</p>
  
  <p>26</p>
  
  <p><strong>Test case 2 (PASS):</strong></p>
  
  <p><code>deleteN(head, 3);</code></p>
  
  <p><code>printList(head);</code></p>
  
  <p><strong>Output:</strong></p>
  
  <p>23</p>
  
  <p>24</p>
  
  <p>26</p>
  
  <p><strong>Test case 3 (PASS):</strong></p>
  
  <p><code>deleteN(head, 4);</code></p>
  
  <p><code>printList(head);</code></p>
  
  <p><strong>Output:</strong></p>
  
  <p>23</p>
  
  <p>24</p>
  
  <p>25</p>
  
  <p><strong>Test case 4 (FAIL):</strong></p>
  
  <p><code>deleteN(head, 1);</code></p>
  
  <p><code>printList(head);</code></p>
  
  <p><strong>Output:</strong></p>
  
  <p>34223223</p>
  
  <p>34234242</p>
  
  <p>34342343</p>
  
  <p>34343434</p>
  
  <p>34234434</p>
  
  <p>(more garbage numbers then segfault)</p>
  
  <p>My question is how can I modify my code so that it can delete the first node as well?</p>