From 817d04c8d6d91a68b6fe3d1a1df3322468ff8f83 Mon Sep 17 00:00:00 2001 From: Mark Kuang Date: Tue, 16 Oct 2018 21:53:21 +0800 Subject: [PATCH] Solution in Ruby 021 --- .../021.Merge Two Sorted Lists/Solution.rb | 39 +++++++++++++++++++ solution/023.Merge k Sorted Lists/Solution.rb | 0 2 files changed, 39 insertions(+) create mode 100644 solution/021.Merge Two Sorted Lists/Solution.rb create mode 100644 solution/023.Merge k Sorted Lists/Solution.rb diff --git a/solution/021.Merge Two Sorted Lists/Solution.rb b/solution/021.Merge Two Sorted Lists/Solution.rb new file mode 100644 index 0000000000000..2e01d135e30cb --- /dev/null +++ b/solution/021.Merge Two Sorted Lists/Solution.rb @@ -0,0 +1,39 @@ +# 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) + return l1 if l2.nil? + return l2 if l1.nil? + + head = ListNode.new(0) + temp = head + + until l1.nil? && l2.nil? + if l1.nil? + head.next = l2 + break + elsif l2.nil? + head.next = l1 + break + elsif l1.val < l2.val + head.next = ListNode.new(l1.val) + head = head.next + l1 = l1.next + else + head.next = ListNode.new(l2.val) + head = head.next + l2 = l2.next + end + end + temp.next +end + diff --git a/solution/023.Merge k Sorted Lists/Solution.rb b/solution/023.Merge k Sorted Lists/Solution.rb new file mode 100644 index 0000000000000..e69de29bb2d1d