I have the following code. I create 2 linked lists (l1 and l2) and I would like to combine them together to one sorted linked list. I use the recursive function merge_lists for this and I get error.
class Node(object):
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class LinkedList:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = Node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print (node.data)
node = node.next
def merge_lists(h1, h2):
if h1 is None:
return h2
if h2 is None:
return h1
if (h1.data < h2.data):
h1.next = merge_lists(h1.next, h2)
return h1
else:
h2.next = merge_lists(h2.next, h1)
return h2
l1 = LinkedList()
l1.add_node(1)
l1.add_node(5)
l1.add_node(7)
ll.list_print()
l2= LinkedList()
l2.add_node(2)
l2.add_node(6)
l2.add_node(8)
l2.list_print()
merge_lists(l1, l2)
Here is the error I get:
7
5
1
8
6
2
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-59-5032e795cb05> in <module>()
49 l2.list_print()
50
---> 51 merge_lists(l1, l2)
<ipython-input-59-5032e795cb05> in merge_lists(h1, h2)
27 return h1
28
---> 29 if (h1.data < h2.data):
30 h1.next = merge_lists(h1.next, h2)
31 return h1
AttributeError: 'str' object has no attribute 'data'