21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
# 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} l1
# @param {ListNode} l2
# @return {ListNode}
def merge_two_lists(l1, l2)
new_node = current_node = ListNode.new(0)
while l1 || l2
if l1 && l2
if l1.val <= l2.val
current_node.next = l1
l1 = l1.next
current_node = current_node.next
else
current_node.next = l2
l2 = l2.next
current_node = current_node.next
end
elsif l1 && l2.nil?
current_node.next = l1
return new_node.next
elsif l2 && l1.nil?
current_node.next = l2
return new_node.next
end
end
return new_node.next
end
Last updated
Was this helpful?