Data structures · 11 / 15 Exercise Hard

Merge sorted lists

Objective

Create a Python program that merges two sorted linked lists into a single sorted list by reusing the nodes, without creating an intermediate Python list to sort.

Instructions

  • Read two lines, each with integers already sorted from lowest to highest and separated by spaces (each line has at least one number). Build two linked lists from them with a Node class.
  • Write a function merge(a, b) that walks both lists at once, always linking the node with the smaller value (if they are equal, the one from the first list first).
  • Show the resulting list with the values separated by -> .
Input
1 4 7
2 3 9
Output
1 -> 2 -> 3 -> 4 -> 7 -> 9

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise