private ListNode merge(ListNode head1, ListNode head2) {

    ListNode dummy = new ListNode(0);
    ListNode head = dummy;

    while (head1 != null && head2 != null) {
      if (head1.val <= head2.val) {
        head.next = head1;
        head1 = head1.next;
      } else {
        head.next = head2;
        head2 = head2.next;
      }
      head = head.next;
    }

    if (head1 == null) {
      head.next = head2;
    } else if (head2 == null) {
      head.next = head1;
    }

    return dummy.next;
  }