Skip to content

Commit 22ff96c

Browse files
committed
merge two sorted lists solution
1 parent 28bf5d3 commit 22ff96c

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
# Use a while loop to compare values and build the merged list
9+
10+
# Create a new list
11+
output = ListNode()
12+
cur = output
13+
14+
while list1 and list2:
15+
if list1.val < list2.val:
16+
cur.next = list1
17+
list1 = list1.next
18+
else:
19+
cur.next = list2
20+
list2 = list2.next
21+
22+
cur = cur.next
23+
24+
# Attach the remaining nodes
25+
cur.next = list1 or list2
26+
27+
return output.next

0 commit comments

Comments
 (0)