FAQ: Technical Interview Problems in Python: Linked Lists - Merge Sorted Linked Lists

This community-built FAQ covers the “Merge Sorted Linked Lists” exercise from the lesson “Technical Interview Problems in Python: Linked Lists”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Technical Interview Practice: Python

FAQs on the exercise Merge Sorted Linked Lists

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi,

The CodeCademy solution is very difficult to understand me.

I created my own solution. It is alter the list of smaller header.

And my opinion is we don’t have to place this function outside of the Linked_list class. If we can alter the original list, then this method belong to the class.

My solution
def merge(linked_list_a, linked_list_b):
  current_a_node = linked_list_a.head
  current_b_node = linked_list_b.head
  if current_a_node.val > current_b_node.val:
    # swap to start with the smaller header:
    current_a_node, current_b_node = current_b_node, current_a_node
  
  while current_b_node:
    if current_a_node.next.val < current_b_node.val:
      # got to next a:
      current_a_node = current_a_node.next
    else:
      # cut both list:
      temporary_a = current_a_node.next 
      temporary_b = current_b_node.next 

      # insert 'current b':
      current_a_node.next = current_b_node
      # merge the cutted lists:
      current_a_node.next.next = temporary_a
      current_b_node = temporary_b 
  
  return linked_list_a
1 Like

Keep going the good work.Codecademy solution makes difficult to understand the problem.