keep learning, keep coding!
Problem - Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
翻譯蒟蒻
將兩個已排序的鏈表整合成一個新的已排序鏈表,並返回新鏈表的 head。
Example 1:
1 2
| Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
|
Example 2:
1 2
| Input: list1 = [], list2 = [] Output: []
|
Example 3:
1 2
| Input: list1 = [], list2 = [0] Output: [0]
|
Solution - JavaScript
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
|
var mergeTwoLists = function(list1, list2) { let dummy = new ListNode(0); let curr = dummy; while (list1 && list2) { if (list1.val < list2.val) { curr.next = list1; list1 = list1.next; } else { curr.next = list2; list2 = list2.next; } curr = curr.next; } curr.next = list1 || list2; return dummy.next; };
|
Solution - Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def merge_two_lists(list1, list2) dummy_head = ListNode.new current = dummy_head
while list1 && list2 if list1.val < list2.val current.next = list1 list1 = list1.next else current.next = list2 list2 = list2.next end current = current.next end
current.next = list1 || list2
dummy_head.next end
|
Solution - PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function mergeTwoLists($list1, $list2) { $dummy = new ListNode(0); $cur = $dummy; while ($list1 && $list2) { if ($list1->val < $list2->val) { $cur->next = $list1; $list1 = $list1->next; } else { $cur->next = $list2; $list2 = $list2->next; } $cur = $cur->next; } $cur->next = $list1 ? $list1 : $list2; return $dummy->next; }
|
LeetCode 傳送門 - Merge Two Sorted Lists