munch2024 / munch

2 stars 11 forks source link

Understanding Complex Code Task 2.3 #123

Closed Fabrizv closed 8 months ago

Fabrizv commented 8 months ago

This code is from my LeetCode. It has the user merge two sorted lists into one. Goals:

  1. Have ChatGPT explain how the code works
  2. Incorporate in optimizations it suggests
  3. Add documentation

Code Snippet:

# 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]:
        temp = ListNode()
        tail = temp
        while True:

            if list1 is None:
                tail.next = list2
                break
            elif list2 is None:
                tail.next = list1
                break

            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next

            tail = tail.next
            # print(f'temp val = {curr.val}')

        return temp.next