LeetCode-in-Ruby.github.io

21. Merge Two Sorted Lists

Easy

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.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]

Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []

Output: []

Example 3:

Input: l1 = [], l2 = [0]

Output: [0]

Constraints:

Solution

# Definition for singly-linked list.
# class ListNode
#     attr_accessor :val, :next
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end
# @param {ListNode} list1
# @param {ListNode} list2
# @return {ListNode}
def merge_two_lists(list1, list2)
  list = ListNode.new(-1)
  head = list

  while list1 || list2
    if list1 && list2
      if list1.val <= list2.val
        list.next = ListNode.new(list1.val)
        list1 = list1.next
      else
        list.next = ListNode.new(list2.val)
        list2 = list2.next
      end
    elsif list1
      list.next = ListNode.new(list1.val)
      list1 = list1.next
    else
      list.next = ListNode.new(list2.val)
      list2 = list2.next
    end

    list = list.next
  end

  head.next
end