File tree Expand file tree Collapse file tree 2 files changed +47
-30
lines changed Expand file tree Collapse file tree 2 files changed +47
-30
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments