Issue
For example, merge 2 sorted linked lists. I understand the code for solving the problem. However, how to create two linked lists and see the output? I have the same problem with trees. If I know how to test the input, it will be very helpful.
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
# 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:
Solution
For testing solutions with linked lists it helps to have functions (or methods) which translate linked lists to lists and vice versa. So define these:
def to_linked_list(iterable):
head = None
for val in reversed(iterable):
head = ListNode(val, head)
return head
def to_native_list(head):
lst = []
while head:
lst.append(head.val)
head = head.next
return lst
Now you can more easily test your solution:
l1 = to_linked_list([1,2,4])
l2 = to_linked_list([1,3,4])
result = Solution().mergeTwoLists(l1, l2)
print(to_native_list(result))
Answered By - trincot Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.