title: understanding Linked list and and Reference types
body: <p>I'm struggling with how this code works for several days. I've learned about linked list and reference types, but I cannot perceive them well. Could someone clear it up for me?</p>
  <p>It's code that merges and sorts two <code>NodeList</code> together that you might see in some interview questions and it is categorized in easy questions. :)</p>
  <pre><code>public ListNode MergeTwoLists(ListNode l1, ListNode l2)
  {
      var head = new ListNode(-1);
      var current = head;
    
      while (l1 != null &amp;&amp; l2 != null)
      {
          if (l1.val &lt;= l2.val)
          {
              current.next = l1;
              l1 = l1.next;
          }
          else
          {
              current.next = l2;
              l2 = l2.next;
          }
          current = current.next;
      }
      current.next = l1 == null ? l2 : l1;
      return head.next;
  }
  </code></pre>
  <p>So let's suppose these two list:</p>
  <pre><code>l1: [1, 3, 5]
  l2: [2, 4, 6]
  </code></pre>
  <p>I have two problems:</p>
  <ol>
  <li><p>As far as I know that classes in C# are reference types so the value of <code>current</code> and <code>head</code> must remain the same as each other. For example after executing <code>current = current.next;</code> the value of <code>head</code> remain as it was.</p>
  </li>
  <li><p>In the second iteration while the value of <code>l2=2</code> and is less than <code>l1=3</code> this line executes <code>current.next = l2;</code> and the value of <code>head</code> changes weirdly. the <code>next</code> node in <code>head</code> has the value of <code>1</code> and the next node has the value of <code>2</code>. How did this happen?</p>
  </li>
  </ol>
  <p><strong>UPDATE:</strong></p>
  <p>How <code>current.next = l2</code> refers to proper position of <code>head</code>? I mean when <code>head</code> has these values: 1, 3, 5 after executing this line it becomes 1, 2, 4, 6. Why <code>1</code> remains in <code>head</code>? and for the next iteration, we will have something like this: 1, 2, 3, 5, and again why <code>1, 2,</code> remains in the head? How does it recognize where is the best place to insert a new item?</p>