|
| 1 | +# Learn Python together |
| 2 | +"""You are given the heads of two sorted linked lists list1 and list2. |
| 3 | +Merge the two lists in a one sorted list. The list should be made by |
| 4 | +splicing together the nodes of the first two lists. |
| 5 | +Return the head of the merged linked list.""" |
| 6 | + |
| 7 | +# Solution |
| 8 | +# import Optional type |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +#Definition for singly-linked list. |
| 12 | +class ListNode: |
| 13 | + def __init__(self, val=0, next=None): |
| 14 | + self.val = val |
| 15 | + self.next = next |
| 16 | +class Solution: |
| 17 | + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]): |
| 18 | + |
| 19 | + if not list1 or not list2: # If one of the lists is empty, |
| 20 | + return list1 or list2 # return the other list |
| 21 | + # comparing lists values for getting lower value |
| 22 | + if list1.val < list2.val: |
| 23 | + # lover value from list1 |
| 24 | + head = list1 |
| 25 | + # using recursive get other values in tail variable |
| 26 | + tail = self.mergeTwoLists(list1.next, list2) |
| 27 | + else: # if the value of second node is lower than first node |
| 28 | + # lover value from list2 |
| 29 | + head = list2 |
| 30 | + # using recursive get other values in tail variable |
| 31 | + tail = self.mergeTwoLists(list1, list2.next) |
| 32 | + # connects the head node and the tail node of the merged linked list |
| 33 | + head.next = tail |
| 34 | + return head # return current node |
| 35 | + |
| 36 | +#check |
| 37 | +list1 = ListNode(1, ListNode(2, ListNode(4))) |
| 38 | +list2 = ListNode(1, ListNode(3, ListNode(4))) |
| 39 | +solution = Solution() |
| 40 | +result = solution.mergeTwoLists(list1, list2) |
| 41 | +expected_result = ListNode(1, ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(4)))))) |
| 42 | + |
| 43 | +# funtion to printing linked-list result |
| 44 | +def print_list(head): |
| 45 | + node = head |
| 46 | + while node: |
| 47 | + # print current value and '->' if there is a next value in linked-list else empty string |
| 48 | + print(node.val, end=" -> " if node.next else "") |
| 49 | + # moving to next value |
| 50 | + node = node.next |
| 51 | + print() |
| 52 | + |
| 53 | +print_list(result) |
| 54 | +# Output -> 1 -> 1 -> 2 -> 3 -> 4 -> 4 |
| 55 | +print_list(expected_result) |
| 56 | +# Output -> 1 -> 1 -> 2 -> 3 -> 4 -> 4 |
| 57 | + |
0 commit comments