title: Manual Linked List - Insert before method
body: <p>This is part of an exercise we did in class, I just can't figure it out...</p>
  
  <p>The required method is the insertBefore(object data) method wherein when a user choose this method it will prompt it to enter a data to be inserted before the reference data(input by user)</p>
  
  <p>An example of how it should run:</p>
  
  <pre class="lang-none prettyprint-override"><code>// assuming linked list has data 1,2,3 inserted already
  
  Choose Method:
  1)Insert Before
  
  choice: 1 // input by user
  
  
  ====Insert Before====
  Enter Reference data: 2 // input by user
  Enter Data to be inserted: 5 // input by user
  
  supposed output: 1,5,2,3
  </code></pre>
  
  <p>Here's my code for this exercise: (This is inside a class called LinkList with variables</p>
  
  <pre><code>protected int end;
  protected Node start;
  </code></pre>
  
  <p>and an inner class called Node)</p>
  
  <pre><code>private class Node
  {
      public char data;
      public Node next;
      public Node(char data)
      {
          this.data = data;
      }
  }
  
  
  public void insertBef(char ref,char data)
  {
      Node temp = new Node(data);
      Node current = start;
  
      if(end!=0)
      {
          for(int i = 1; i&lt;end; i++)
          {
              if(current == start)
              {
                  Node newNode = start;
                  newNode.data = current.data;
                  newNode.next = temp;
                  current = current.next;
              }
              else if(current.data == ref)
              {
                  Node newNode = current;
                  newNode.data = current.data;
                  newNode.next = temp;
                  current = current.next;
              }
          }
          end++;
  
      }
      else
      {
          temp.next = start;
          start = temp;
      }
      end++;
  }
  </code></pre>
  
  <p>But when I run my code it ouputs <code>3,5</code>, not <code>1,5,2,3</code>! I can't see where I might have gone wrong...</p>
  
  <p>Can someone please tell me where the mistake is, and explain how I might fix it?</p>
  
  <p>I understand that to be able to insert before a reference value you should:</p>
  
  <ul>
  <li>Make a new node for the new data</li>
  <li>Make a temporary node for the reference value and link</li>
  <li>Make the link of the data before the reference value point to the new node and make the link of the new node point to the temporary node</li>
  </ul>
  
  <p>I just can't seem to figure out how to implement it in Java code...</p>