jinhuang1102

21. Merge Two Sorted Lists

Oct 20th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. class Solution:
  2.     def mergeTwoLists(self, l1, l2):
  3.         """
  4.        :type l1: ListNode
  5.        :type l2: ListNode
  6.        :rtype: ListNode
  7.        """
  8.         if not l1 or not l2:
  9.             return l1 or l2
  10.        
  11.         res = ListNode(0)
  12.         head = res
  13.        
  14.         temp1 = l1
  15.         temp2 = l2
  16.         while temp1 and temp2:
  17.             if temp1.val <= temp2.val:
  18.                 head.next = temp1
  19.                 temp1 = temp1.next
  20.             else:
  21.                 head.next = temp2
  22.                 temp2 = temp2.next
  23.                
  24.             head = head.next
  25.            
  26.         remain = temp1 or temp2
  27.         head.next = remain
  28.        
  29.         return res.next
Add Comment
Please, Sign In to add comment