21. Merge Two Sorted Lists
O(n)
  1. from typing import List
  2.  
  3. # Definition for singly-linked list.
  4. class ListNode:
  5. def __init__(self, x):
  6. self.val = x
  7. self.next = None
  8.  
  9. class Solution:
  10. def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
  11. w1 = l1
  12. w2 = l2
  13.  
  14. l = ListNode(0)
  15. w = l
  16.  
  17. while w1 is not None and w2 is not None:
  18. if w1.val < w2.val:
  19. w.next = ListNode(w1.val)
  20. w1 = w1.next
  21. else:
  22. w.next = ListNode(w2.val)
  23. w2 = w2.next
  24. w = w.next
  25.  
  26. if w1 is not None:
  27. while w1 is not None:
  28. w.next = ListNode(w1.val)
  29. w1 = w1.next
  30. w = w.next
  31.  
  32. if w2 is not None:
  33. while w2 is not None:
  34. w.next = ListNode(w2.val)
  35. w2 = w2.next
  36. w = w.next
  37.  
  38. return l.next
  39.  
  40. def getList(l: List[int]) -> ListNode:
  41. head = None
  42. if not l:
  43. return head
  44.  
  45. head = ListNode(l[0])
  46. walker = head
  47. for i in range(1, len(l)):
  48. walker.next = ListNode(l[i])
  49. walker = walker.next
  50.  
  51. return head
  52.  
  53. def disp(l: ListNode) -> None:
  54. walker = l
  55.  
  56. while walker is not None:
  57. print('-> '+str(walker.val), end = ' ')
  58. walker = walker.next
  59. print()
  60.  
  61. def main():
  62. l1 = getList([1, 2, 4])
  63. l2 = getList([1, 3, 4])
  64.  
  65. disp(l1)
  66. disp(l2)
  67.  
  68. s = Solution()
  69. l = s.mergeTwoLists(l1, l2)
  70.  
  71. disp(l)
  72.  
  73. if __name__ == '__main__':
  74. main()
  75.