From 711434b7aaeac64a516705253bef7ba68672601d Mon Sep 17 00:00:00 2001 From: yayyz Date: Fri, 25 Apr 2025 23:45:08 +0900 Subject: [PATCH] merge two sorted lists --- merge-two-sorted-lists/yayyz.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 merge-two-sorted-lists/yayyz.py diff --git a/merge-two-sorted-lists/yayyz.py b/merge-two-sorted-lists/yayyz.py new file mode 100644 index 000000000..bdb9b01ef --- /dev/null +++ b/merge-two-sorted-lists/yayyz.py @@ -0,0 +1,25 @@ +# 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]: + dummy = ListNode(0) + current = dummy + + while list1 is not None and list2 is not None: + if list1.val < list2.val: + current.next = list1 + list1 = list1.next + else: + current.next = list2 + list2 = list2.next + current = current.next + + if list1 is not None: + current.next = list1 + else: + current.next = list2 + + return dummy.next