title: Split linked list into half
body: <p>I am trying to create a function splitlist(), which will split a singly linked list into two sublists – one for the front half, and one for the back half. I have come up with a code below which will work for the first time that I call the function, but when I call the function repeatedly, the program crashes. Any advice on how I can change my code to prevent such an error? The function splitlist() is void as it prints two lists which contains frontList and backList.</p>
  
  <pre><code>typedef struct _listnode {
  int item;
  struct _listnode *next;
  } ListNode;         
  
  typedef struct _linkedlist {
  int size;
  ListNode *head;
  } LinkedList;   
  
      void splitlist(LinkedList* list1, LinkedList * firsthalf, LinkedList *secondhalf)       
  {
      ListNode *cur = list1-&gt;head;
      ListNode *front = firsthalf-&gt;head;
      ListNode *back = secondhalf-&gt;head;
      int totalnodes = list1-&gt;size;
      int i;
      if (totalnodes % 2 != 0)                    //if odd number of elements, add 1 to make it easier for traversal of list
      {
          totalnodes = totalnodes + 1;
      }
      int halfnodes = totalnodes / 2;
  
  
      {
          for (i = 0; i &lt; halfnodes; i++)             
          {
              if (firsthalf-&gt;head == NULL)        //initialise the head
              {
                  firsthalf-&gt;head = malloc(sizeof(ListNode)); //create first node
                  front = firsthalf-&gt;head;
              }
              else
              {
                  front-&gt;next = malloc(sizeof(ListNode));     
                  front = front-&gt;next;                        
              }
              front-&gt;item = cur-&gt;item;                    // insert value from list1 into firsthalf
              cur = cur-&gt;next;                            //point to next node in list1
  
          }
          front-&gt;next = NULL;     //last node
  
          for (i = halfnodes; i &lt; totalnodes; i++)            
          {
              if (secondhalf-&gt;head == NULL)
              {
                  secondhalf-&gt;head = malloc(sizeof(ListNode));
                  back = secondhalf-&gt;head;
              }
              else
              {
                  back-&gt;next = malloc(sizeof(ListNode));
                  back = back-&gt;next;
              }
              back-&gt;item = cur-&gt;item;
              cur = cur-&gt;next;
  
          }
          back-&gt;next = NULL;
      }
  
  }
  </code></pre>