Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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, l1: ListNode, l2: ListNode) -> ListNode:
- # Handle edge cases where either or both lists are None
- if not l1:
- return l2
- if not l2:
- return l1
- result_head = None
- result_tail = None
- # Keep track of pointers #1 and #2
- p1 = l1
- p2 = l2
- # While neither pointer #1 and #2 have reached end of their respective LLs:
- while p1 and p2:
- # If p1 <= p2:
- if p1.val <= p2.val:
- # Keep track of p1's original next node
- l1_next_node = p1.next
- # Reset p1.next to avoid circular pointers
- p1.next = None
- # Add p1 to result
- # If this is the 1st node in the result, set result head
- if not result_head:
- result_head = p1
- # If this is NOT the 1st node in the result, add p1 to end of result
- else:
- result_tail.next = p1
- # Increment result_tail
- result_tail = p1
- # Increment p1
- p1 = l1_next_node
- # Else (if p2 > p1)
- else:
- # Add p2 to result
- l2_next_node = p2.next
- p2.next = None
- if not result_head:
- result_head = p2
- else:
- result_tail.next = p2
- # Increment result_tail
- result_tail = p2
- # Increment p2
- p2 = l2_next_node
- # If p1 is None:
- if not p1:
- # Add rest of p2's list to result
- result_tail.next = p2
- # Else
- else:
- # Add rest of p1's list to result
- result_tail.next = p1
- # Return result_head
- return result_head
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement