TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
Below is an iterative solution to the weave_spells()
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 weave_spells(spell_a, spell_b):
# If either list is empty, return the other
if not spell_a:
return spell_b
if not spell_b:
return spell_a
# Start with the first node of spell_a
head = spell_a
# Loop through both lists until one is exhausted
while spell_a and spell_b:
# Store the next pointers
next_a = spell_a.next
next_b = spell_b.next
# Weave spell_b after spell_a
spell_a.next = spell_b
# If there's more in spell_a, weave it after spell_b
if next_a:
spell_b.next = next_a
# Move to the next nodes
spell_a = next_a
spell_b = next_b
# Return the head of the new woven list
return head
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def weave_spells(spell_a, spell_b):
# Base cases
if not spell_a:
return spell_b
if not spell_b:
return spell_a
# Weave the current nodes
spell_a.next = weave_spells(spell_b, spell_a.next)
# Return the new head of the list
return spell_a
spell_a
and spell_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: