smj007

Untitled

Jul 30th, 2023 (edited)
1,197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  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. """
  7. Approach 2: Iteration
  8.  
  9. Intuition
  10.  
  11. We can achieve the same idea via iteration by assuming that l1 is entirely
  12. less than l2 and processing the elements one-by-one, inserting elements of
  13. l2 in the necessary places in l1.
  14.  
  15. Algorithm
  16.  
  17. First, we set up a false "prehead" node that allows us to easily return the
  18. head of the merged list later. We also maintain a prev pointer, which
  19. points to the current node for which we are considering adjusting its next
  20. pointer. Then, we do the following until at least one of l1 and l2 points
  21. to null: if the value at l1 is less than or equal to the value at l2,
  22. then we connect l1 to the previous node and increment l1. Otherwise, we
  23. do the same, but for l2. Then, regardless of which list we connected, we
  24. increment prev to keep it one step behind one of our list heads.
  25.  
  26. After the loop terminates, at most one of l1 and l2 is non-null.
  27. Therefore (because the input lists were in sorted order), if either list is
  28. non-null, it contains only elements greater than all of the
  29. previously-merged elements. This means that we can simply connect the
  30. non-null list to the merged list and return it.
  31.  
  32. """
  33.  
  34. To see this in action on an example, check out the animation below:
  35.  
  36. class Solution:
  37.     def mergeTwoLists(self, first: Optional[ListNode], second: Optional[ListNode]) -> Optional[ListNode]:
  38.  
  39.         dummy = ListNode(-101)
  40.         temp = dummy
  41.  
  42.         while(first and second):
  43.             if first.val <= second.val:
  44.                 dummy.next = first
  45.                 first = first.next
  46.             else:
  47.                 dummy.next = second
  48.                 second = second.next
  49.             dummy = dummy.next
  50.            
  51.         if not first:
  52.             dummy.next = second
  53.  
  54.         if not second:
  55.             dummy.next = first
  56.  
  57.         return temp.next
  58.  
Advertisement
Add Comment
Please, Sign In to add comment