【Leetcode】21. Merge Two Sorted Lists

Description

https://leetcode.com/problems/merge-two-sorted-lists/

1
2
3
4
5
6
Merge two sorted linked lists and return it as a new 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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end

# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def merge_two_lists(l1, l2)
head = ListNode.new(nil)
current_node = head

while !l1.nil? && !l2.nil? do
if l1.val <= l2.val
current_node.next = l1
l1 = l1.next
else
current_node.next = l2
l2 = l2.next
end
current_node = current_node.next
end

if !l1.nil?
current_node.next = l1
end

if !l2.nil?
current_node.next = l2
end

head.next
end