Skip to content

Commit 84cf55a

Browse files
committed
21. Merge Two Sorted Lists
```Solution.c /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) { struct ListNode* merged = NULL; struct ListNode** lastPtr = &merged; while (list1 && list2) { struct ListNode* newNode = malloc(sizeof(struct ListNode)); if (!newNode) { return NULL; } if (list1->val < list2->val) { newNode->val = list1->val; list1 = list1->next; } else { newNode->val = list2->val; list2 = list2->next; } newNode->next = NULL; *lastPtr = newNode; lastPtr = &newNode->next; } *lastPtr = list1 ? list1 : list2; return merged; } ``` ```Solution.cpp /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { ListNode* merged = nullptr; ListNode** lastPtr = &merged; while (list1 && list2) { ListNode* newNode = new ListNode(); if (!newNode) { return nullptr; } if (list1->val < list2->val) { newNode->val = list1->val; list1 = list1->next; } else { newNode->val = list2->val; list2 = list2->next; } newNode->next = nullptr; *lastPtr = newNode; lastPtr = &newNode->next; } *lastPtr = list1 ? list1 : list2; return merged; } }; ``` ```Solution.cs /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode MergeTwoLists(ListNode list1, ListNode list2) { ListNode merged = new ListNode(0); ListNode current = merged; while (list1 != null && list2 != null) { if (list1.val < list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } current.next = list1 ?? list2; return merged.next; } } ``` ```Solution.dart /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode? next; * ListNode([this.val = 0, this.next]); * } */ class Solution { ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { ListNode? merged = ListNode(); ListNode? current = merged; while (list1 != null && list2 != null) { if (list1.val < list2.val) { current?.next = list1; list1 = list1.next; } else { current?.next = list2; list2 = list2.next; } current = current?.next; } current?.next = list1 ?? list2; return merged?.next; } } ``` ```Solution.erl %% Definition for singly-linked list. %% %% -record(list_node, {val = 0 :: integer(), %% next = null :: 'null' | #list_node{}}). -spec merge_two_lists(List1 :: #list_node{} | null, List2 :: #list_node{} | null) -> #list_node{} | null. merge_two_lists(null, List2) -> List2; merge_two_lists(List1, null) -> List1; merge_two_lists(List1 = #list_node{val = V1, next = Next1}, List2 = #list_node{val = V2, next = Next2}) -> if V1 =< V2 -> #list_node{val = V1, next = merge_two_lists(Next1, List2)}; true -> #list_node{val = V2, next = merge_two_lists(List1, Next2)} end. ``` ```Solution.ex # Definition for singly-linked list. # # defmodule ListNode do # @type t :: %__MODULE__{ # val: integer, # next: ListNode.t() | nil # } # defstruct val: 0, next: nil # end defmodule Solution do @SPEC merge_two_lists(list1 :: ListNode.t | nil, list2 :: ListNode.t | nil) :: ListNode.t | nil def merge_two_lists(nil, list2), do: list2 def merge_two_lists(list1, nil), do: list1 def merge_two_lists(%{val: v1, next: n1} = list1, %{val: v2, next: n2} = list2) do if v1 <= v2 do %ListNode{val: v1, next: merge_two_lists(n1, list2)} else %ListNode{val: v2, next: merge_two_lists(list1, n2)} end end end ``` ```Solution.go /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { if list1 == nil { return list2 } if list2 == nil { return list1 } if list1.Val < list2.Val { list1.Next = mergeTwoLists(list1.Next, list2) return list1 } list2.Next = mergeTwoLists(list1, list2.Next) return list2 } ``` ```Solution.java /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(0); ListNode current = dummy; while (list1 != null && list2 != null) { if (list1.val < list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if (list1 != null) { current.next = list1; } else { current.next = list2; } return dummy.next; } } ``` ```Solution.js /** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} list1 * @param {ListNode} list2 * @return {ListNode} */ var mergeTwoLists = function(list1, list2) { if (!list1) return list2; if (!list2) return list1; if (list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } }; ``` ```Solution.kt /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { val dummy = ListNode(0) var tail = dummy var l1 = list1 var l2 = list2 while (l1 != null && l2 != null) { if (l1.`val` < l2.`val`) { tail.next = l1 l1 = l1.next } else { tail.next = l2 l2 = l2.next } tail = tail.next!! } tail.next = l1 ?: l2 return dummy.next } } ``` ```Solution.php /** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val = 0, $next = null) { * $this->val = $val; * $this->next = $next; * } * } */ class Solution { /** * @param ListNode $list1 * @param ListNode $list2 * @return ListNode */ function mergeTwoLists($list1, $list2) { $dummy = new ListNode(0); $current = $dummy; while ($list1 !== null && $list2 !== null) { if ($list1->val < $list2->val) { $current->next = $list1; $list1 = $list1->next; } else { $current->next = $list2; $list2 = $list2->next; } $current = $current->next; } if ($list1 !== null) { $current->next = $list1; } else { $current->next = $list2; } return $dummy->next; } } ``` ```Solution.py # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: if not list1: return list2 if not list2: return list1 if list1.val <= list2.val: list1.next = self.mergeTwoLists(list1.next, list2) return list1 else: list2.next = self.mergeTwoLists(list1, list2.next) return list2 ``` ```Solution.rb # 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) dummy = ListNode.new current = dummy 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.next end ``` ```Solution.rkt ; Definition for singly-linked list: #| ; val : integer? ; next : (or/c list-node? #f) (struct list-node (val next) #:mutable #:transparent) ; constructor (define (make-list-node [val 0]) (list-node val #f)) |# (define/contract (merge-two-lists list1 list2) (-> (or/c list-node? #f) (or/c list-node? #f) (or/c list-node? #f)) (cond [(not list1) list2] [(not list2) list1] [(<= (list-node-val list1) (list-node-val list2)) (set-list-node-next! list1 (merge-two-lists (list-node-next list1) list2)) list1] [else (set-list-node-next! list2 (merge-two-lists list1 (list-node-next list2))) list2])) ``` ```Solution.rs use crate::list_node::ListNode; impl Solution { pub fn merge_two_lists( mut list1: Option<Box<ListNode>>, mut list2: Option<Box<ListNode>>, ) -> Option<Box<ListNode>> { let mut dummy = Box::new(ListNode { val: 0, next: None }); let mut tail = &mut dummy; while list1.is_some() && list2.is_some() { let l1_val = list1.as_ref().unwrap().val; let l2_val = list2.as_ref().unwrap().val; if l1_val < l2_val { let next = list1.as_mut().unwrap().next.take(); tail.next = list1; tail = tail.next.as_mut().unwrap(); list1 = next; } else { let next = list2.as_mut().unwrap().next.take(); tail.next = list2; tail = tail.next.as_mut().unwrap(); list2 = next; } } tail.next = if list1.is_some() { list1 } else { list2 }; dummy.next } } ``` ```Solution.scala /** * Definition for singly-linked list. * class ListNode(_x: Int = 0, _next: ListNode = null) { * var next: ListNode = _next * var x: Int = _x * } */ object Solution { def mergeTwoLists(list1: ListNode, list2: ListNode): ListNode = { if (list1 == null) return list2 if (list2 == null) return list1 if (list1.x < list2.x) { list1.next = mergeTwoLists(list1.next, list2) list1 } else { list2.next = mergeTwoLists(list1, list2.next) list2 } } } ``` ```Solution.swift /** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } * } */ class Solution { func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? { let dummy = ListNode(0) var current = dummy var l1 = list1 var l2 = list2 while l1 != nil && l2 != nil { if l1!.val < l2!.val { current.next = l1 l1 = l1!.next } else { current.next = l2 l2 = l2!.next } current = current.next! } current.next = l1 ?? l2 return dummy.next } } ``` ```Solution.ts /** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { if (!list1) return list2; if (!list2) return list1; if (list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } }; ```
1 parent 14de6d5 commit 84cf55a

20 files changed

+494
-0
lines changed

res/ino/481517543.jpg

25.8 KB
Loading
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# [**21. Merge Two Sorted Lists**](https://leetcode.com/problems/merge-two-sorted-lists/description/)
2+
3+
You are given the heads of two sorted linked lists `list1` and `list2`.
4+
5+
Merge the two lists into one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
6+
7+
Return the head of the merged linked list.
8+
9+
#### **Example 1:**
10+
11+
<img src="https://raw.githubusercontent.com/leetcoin-releases/leetcode/refs/heads/main/res/ino/481517543.jpg" style="width: 100%; height: 600;"/>
12+
13+
```md
14+
Input: list1 = [1,2,4], list2 = [1,3,4]
15+
Output: [1,1,2,3,4,4]
16+
```
17+
18+
#### **Example 2:**
19+
```md
20+
Input: list1 = [], list2 = []
21+
Output: []
22+
```
23+
24+
#### **Example 3:**
25+
```md
26+
Input: list1 = [], list2 = [0]
27+
Output: [0]
28+
```
29+
30+
#### **Constraints:**
31+
> - The number of nodes in both lists is in the range `[0, 50]`.
32+
> - `-100 <= Node.val <= 100`
33+
> - Both `list1` and `list2` are sorted in **non-decreasing** order.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* struct ListNode *next;
6+
* };
7+
*/
8+
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
9+
struct ListNode* merged = NULL;
10+
struct ListNode** lastPtr = &merged;
11+
while (list1 && list2) {
12+
struct ListNode* newNode = malloc(sizeof(struct ListNode));
13+
if (!newNode) {
14+
return NULL;
15+
}
16+
if (list1->val < list2->val) {
17+
newNode->val = list1->val;
18+
list1 = list1->next;
19+
} else {
20+
newNode->val = list2->val;
21+
list2 = list2->next;
22+
}
23+
newNode->next = NULL;
24+
*lastPtr = newNode;
25+
lastPtr = &newNode->next;
26+
}
27+
*lastPtr = list1 ? list1 : list2;
28+
return merged;
29+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
14+
ListNode* merged = nullptr;
15+
ListNode** lastPtr = &merged;
16+
while (list1 && list2) {
17+
ListNode* newNode = new ListNode();
18+
if (!newNode) {
19+
return nullptr;
20+
}
21+
if (list1->val < list2->val) {
22+
newNode->val = list1->val;
23+
list1 = list1->next;
24+
} else {
25+
newNode->val = list2->val;
26+
list2 = list2->next;
27+
}
28+
newNode->next = nullptr;
29+
*lastPtr = newNode;
30+
lastPtr = &newNode->next;
31+
}
32+
*lastPtr = list1 ? list1 : list2;
33+
return merged;
34+
}
35+
};
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* public int val;
5+
* public ListNode next;
6+
* public ListNode(int val=0, ListNode next=null) {
7+
* this.val = val;
8+
* this.next = next;
9+
* }
10+
* }
11+
*/
12+
public class Solution {
13+
public ListNode MergeTwoLists(ListNode list1, ListNode list2) {
14+
ListNode merged = new ListNode(0);
15+
ListNode current = merged;
16+
while (list1 != null && list2 != null) {
17+
if (list1.val < list2.val) {
18+
current.next = list1;
19+
list1 = list1.next;
20+
} else {
21+
current.next = list2;
22+
list2 = list2.next;
23+
}
24+
current = current.next;
25+
}
26+
current.next = list1 ?? list2;
27+
return merged.next;
28+
}
29+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* int val;
5+
* ListNode? next;
6+
* ListNode([this.val = 0, this.next]);
7+
* }
8+
*/
9+
class Solution {
10+
ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) {
11+
ListNode? merged = ListNode();
12+
ListNode? current = merged;
13+
while (list1 != null && list2 != null) {
14+
if (list1.val < list2.val) {
15+
current?.next = list1;
16+
list1 = list1.next;
17+
} else {
18+
current?.next = list2;
19+
list2 = list2.next;
20+
}
21+
current = current?.next;
22+
}
23+
current?.next = list1 ?? list2;
24+
return merged?.next;
25+
}
26+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
%% Definition for singly-linked list.
2+
%%
3+
%% -record(list_node, {val = 0 :: integer(),
4+
%% next = null :: 'null' | #list_node{}}).
5+
-spec merge_two_lists(List1 :: #list_node{} | null, List2 :: #list_node{} | null) -> #list_node{} | null.
6+
merge_two_lists(null, List2) -> List2;
7+
merge_two_lists(List1, null) -> List1;
8+
merge_two_lists(List1 = #list_node{val = V1, next = Next1}, List2 = #list_node{val = V2, next = Next2}) ->
9+
if
10+
V1 =< V2 ->
11+
#list_node{val = V1, next = merge_two_lists(Next1, List2)};
12+
true ->
13+
#list_node{val = V2, next = merge_two_lists(List1, Next2)}
14+
end.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Definition for singly-linked list.
2+
#
3+
# defmodule ListNode do
4+
# @type t :: %__MODULE__{
5+
# val: integer,
6+
# next: ListNode.t() | nil
7+
# }
8+
# defstruct val: 0, next: nil
9+
# end
10+
defmodule Solution do
11+
@spec merge_two_lists(list1 :: ListNode.t | nil, list2 :: ListNode.t | nil) :: ListNode.t | nil
12+
def merge_two_lists(nil, list2), do: list2
13+
def merge_two_lists(list1, nil), do: list1
14+
def merge_two_lists(%{val: v1, next: n1} = list1, %{val: v2, next: n2} = list2) do
15+
if v1 <= v2 do
16+
%ListNode{val: v1, next: merge_two_lists(n1, list2)}
17+
else
18+
%ListNode{val: v2, next: merge_two_lists(list1, n2)}
19+
end
20+
end
21+
end
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* type ListNode struct {
4+
* Val int
5+
* Next *ListNode
6+
* }
7+
*/
8+
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
9+
if list1 == nil {
10+
return list2
11+
}
12+
if list2 == nil {
13+
return list1
14+
}
15+
if list1.Val < list2.Val {
16+
list1.Next = mergeTwoLists(list1.Next, list2)
17+
return list1
18+
}
19+
list2.Next = mergeTwoLists(list1, list2.Next)
20+
return list2
21+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13+
ListNode dummy = new ListNode(0);
14+
ListNode current = dummy;
15+
while (list1 != null && list2 != null) {
16+
if (list1.val < list2.val) {
17+
current.next = list1;
18+
list1 = list1.next;
19+
} else {
20+
current.next = list2;
21+
list2 = list2.next;
22+
}
23+
current = current.next;
24+
}
25+
if (list1 != null) {
26+
current.next = list1;
27+
} else {
28+
current.next = list2;
29+
}
30+
return dummy.next;
31+
}
32+
}

0 commit comments

Comments
 (0)