title: Can't understand when to use dummy node in leetcode questions
body: <p>I am working on the leetcode question 21 (Merge Two Sorted Lists)</p>
  <p><em>Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.</em></p>
  <p><em>Input: l1 = [1,2,4], l2 = [1,3,4]</em></p>
  <p><em>Output: [1,1,2,3,4,4]</em></p>
  <p>A typical python solution looks like this:</p>
  <pre><code>class Solution:
      def mergeTwoLists(self, l1, l2):
          dummy = ListNode(None)
          res = dummy
         # why can't I just define res as res = ListNode(None)
          
          while l1 and l2:
              if l1.val&lt;= l2.val:
                  res.next = l1
                  l1 = l1.next
              else:
                  res.next = l2
                  l2 = l2.next
              res = res.next
              
          if l1: 
              res.next = l1
          if l2:
              res.next = l2
          return dummy.next
  </code></pre>
  <p><strong>My question is:</strong> why can't I just define res as res = ListNode(None) at the beginning and return res.next as the output? What's the function of the dummy node here?</p>
  <p>Although the above code works, I also can't understand why. We initiated <em>res</em> as the dummy node, but we did not change the variable <em>dummy</em> at all in the subsequent code. So dummy should remain as ListNode(None)the entire time, and we should return res.next instead of dummy.next. Then why do we return dummy.next at the end?</p>
  <p>To illustrate better, I think the code above is doing something similar to the below example, which does not make much sense to me</p>
  <pre><code>a = 3
  b = a
  b = b+2  #or any code that changes something in b, but does not change a
  return a # and the output turns out to be a =5, which is clearly a wrong answer
  
  ##############################
  The above linked list did similar things:
  
  dummy = ListNode(None)
  res = dummy
  
  some other code #The while loop that did something to res, but did nothing to dummy
  
  return dummy 
  #how can we possibly get a dummy that is not None, since the while loop did nothing to it?
  </code></pre>