title: Insert node at a certain position in a linked list C++
body: <p>I'm trying to insert a node at a certain position. In my code, the numbers with position 1 is only being inserted (basically at the beginning of the linked list) and it is not inserting any data with position 2. Is there something wrong with temp2? When I ran the program it is not pointing to anything I think. </p>
  
  <p>I know how much you guys hate homework problems being asked here but I just don't know what is wrong with my program. I'm just a beginner at this and my teacher didn't explain linked list well.</p>
  
  <p>The code is below. </p>
  
  <p>-The output that I'm getting is 8 7 </p>
  
  <p>-I would want it to read 8 6 7 5 where 6 and 5 are inserted at position 2</p>
  
  <pre><code>/*
  Insert node at a given positon in a linked list.
  First element in the linked list is at position 0
  */
  
  #include&lt;stdlib.h&gt;
  #include&lt;stdio.h&gt;
  
  struct Node
  {
     int data;
     struct Node* next;
  };
  
  struct Node *head;
  
  void Insert(int data, int n)
  {
     Node* temp1 = new Node();
     temp1-&gt;data = data;
     temp1-&gt;next = NULL;
     if (n == 1){
      temp1-&gt;next = head;
      head = temp1;
      return;
     }
     Node* temp2 = new Node();
     for (int i = 0; i &lt; n-2; i++){// i feel like it doesn't even go through this loop
      temp2 = temp2-&gt;next;
     }
     temp1-&gt;next = temp2-&gt;next;
     temp2-&gt;next = temp2;
  }
  void print()
  {
      Node* temp = head;
      while(temp != NULL){
          printf("%d ", temp-&gt;data);
          temp = temp-&gt;next;
      }
      printf("\n");
  }
  int main()
  {
      head = NULL; //empty linked list
      Insert(7,1); //List: 7     
      Insert(5,2); //List: 7,5   
      Insert(8,1); //List: 8,7,5 
      Insert(6,2); //List: 8,6,7,5      
      print();
  system("pause");
  } 
  </code></pre>