Question: Leetcode - Easy
The approach to use two pointers: The first one was a dummy ListNode()
and the second is a tail. Then I traverse throught the
list by appending the smaller values of either lists in the tail pointer.
Once the end of the list is gotten to, I then append the remaining nodes to the linked list.
Then the next of the dummy node is returned which points to the first node of the merged linked list.
# 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, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
first = ListNode()
second = first
while list1 is not None and list2 is not None:
if list1.val < list2.val:
second.next = list1
list1 = list1.next
else:
second.next = list2
list2 = list2.next
second = second.next
second.next = list2 if list1 is None else list1
return first.next
- Time Complexity: O(m + n) where m and n are the lengths of the linked list
- Space Complexity: O(1) time is constant because I'm using a constant amount of space to store my dummy node and tail pointer.