Skip to content

Commit c21d39a

Browse files
committed
solve: merge two sorted list
1 parent cf65e7b commit c21d39a

File tree

2 files changed

+47
-30
lines changed

2 files changed

+47
-30
lines changed

merge-two-sorted-lists/sounmind.js

Lines changed: 0 additions & 30 deletions
This file was deleted.

merge-two-sorted-lists/sounmind.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import Optional
2+
3+
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
10+
class Solution:
11+
def mergeTwoLists(
12+
self, list1: Optional[ListNode], list2: Optional[ListNode]
13+
) -> Optional[ListNode]:
14+
"""
15+
Merge two sorted linked lists and return the head of the merged list.
16+
17+
Args:
18+
list1: Head of the first sorted linked list
19+
list2: Head of the second sorted linked list
20+
21+
Returns:
22+
Head of the merged sorted linked list
23+
"""
24+
# Handle edge cases
25+
if not list1:
26+
return list2
27+
if not list2:
28+
return list1
29+
30+
# Create a dummy head to simplify the merging process
31+
dummy_head = ListNode()
32+
current = dummy_head
33+
34+
# Merge nodes from both lists in sorted order
35+
while list1 and list2:
36+
if list1.val < list2.val:
37+
current.next = list1
38+
list1 = list1.next
39+
else:
40+
current.next = list2
41+
list2 = list2.next
42+
current = current.next
43+
44+
# Attach remaining nodes from either list
45+
current.next = list1 if list1 else list2
46+
47+
return dummy_head.next

0 commit comments

Comments
 (0)