TIP102 Unit 7 Session 1 Advanced (Click for link to problem statements)
Below is an iterative solution to the merge_orders()
function from the previous problem. Compare your recursive solution to the iterative solution below.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def merge_orders(sandwich_a, sandwich_b):
# If either list is empty, return the other
if not sandwich_a:
return sandwich_b
if not sandwich_b:
return sandwich_a
# Start with the first node of sandwich_a
head = sandwich_a
# Loop through both lists until one is exhausted
while sandwich_a and sandwich_b:
# Store the next pointers
next_a = sandwich_a.next
next_b = sandwich_b.next
# Merge sandwich_b after sandwich_a
sandwich_a.next = sandwich_b
# If there's more in sandwich_a, add it after sandwich_b
if sandwich_a:
sandwich_b.next = next_a
# Move to the next nodes
sandwich_a = next_a
sandwich_b = next_b
# Return the head of the new merged list
return head
def merge_orders(sandwich_a, sandwich_b):
# Base case: if one of the lists is empty, return the other
if not sandwich_a:
return sandwich_b
if not sandwich_b:
return sandwich_a
# Recursive case: merge first nodes of both lists and recurse
next_a = sandwich_a.next
next_b = sandwich_b.next
sandwich_a.next = sandwich_b
sandwich_b.next = merge_orders(next_a, next_b)
return sandwich_a
sandwich_a
and sandwich_b
are merged into a single linked list in an alternating pattern.Approach:
Complexity:
O(1)
because it uses a constant amount of extra space beyond the input lists.O(N + M)
due to the recursion stack, where N
and M
are the lengths of the two linked lists.O(N + M)
because they process each node exactly once.Performance: