title: Inserting elements in a linked list in various indices using one function only
body: <p>This is the code I tried writing down to add an element in a double linked list, that takes an index and a value and adds a new element to the original list.
  It is taking index and value but just adds the elements I give like a stack.</p>
  <pre><code>node *add(node *head, int index, int val)
  {
  node *new = create(val);
  node *temp = malloc(sizeof(node));
  if (head == NULL)
  {
  head = new;
  temp = head;
  //printf(&quot;:   %d&quot;,temp-&gt;data);
  }
  temp = head;
  int i = 1;
  while (i &lt; (index - 1) &amp;&amp; (temp-&gt;next != NULL))
  {
  i++;
  temp = temp-&gt;next;
  }
  temp-&gt;next = new;
  new-&gt;next = NULL;
  new-&gt;prev = temp;
  return head;
  }
  </code></pre>
  <p>however this code(for a doubly linked list) just adds elements one after the other, disregarding the index passed.
  My prof gave us a code for a singly linked list where he did something similar.</p>
  <pre><code>        struct Node *insert(struct Node *listp, int pos, int info) 
  {
    /*Inserts a Node in list at position pos with data info
      pos&gt;0. If pos&gt;list length then new node added at end.
      If pos&lt;1 adds at beginning.
    */
    struct Node *new=malloc(sizeof(struct Node)), *prev;// new is the new node we create everytime.
    //create new node and initialize fields
    new-&gt;data=info;
    new-&gt;next=NULL;
    if (listp==NULL) listp=new; 
    else
      if (pos&lt;=1) { //negative or 1 index.
        new-&gt;next=listp; //first node bann gaya new
        listp=new; //head is pointing at new
      }
      else {
      //pos&gt;1. Go to node at pos-1.
      prev=listp;
      int i=1;
      while ((i++&lt;pos-1) &amp;&amp; prev-&gt;next!=NULL) { //indexing 
        prev=prev-&gt;next;
      }
      new-&gt;next=prev-&gt;next;
      prev-&gt;next=new;
    }
    return listp;
  }
  </code></pre>
  <p>how do I address this problem?</p>