python - Intersection of two sorted Linked lists in python3? -


my code unable 2 print out new list intersection of 2 sorted linked list.its not able access list inside function. please point out mistake in code. there no indentation problem in code , algorithm seems fine.

class node(object):      def __init__(self,data):         self.data = data         self.next = none  class linked(object):      def __init__(self):         self.head = none      def push(self,n):         new_node = node(n)         new_node.next = self.head         self.head = new_node      def print_list(self):         current = self.head         while current:             print(current.data)             current = current.next      def intersect(self,l1,l2):         l1 = l1.head         l2 = l2.head         dummy = cur = node(0)         while l1 , l2:             if l2.data>l1.data:                 l1=l1.next             elif l1.data>l2.data:                 l2=l2.next             else:                 cur.next = l1 or l2                 l1 = l1.next                 l2 = l2.next             cur = cur.next         return dummy.next llist = linked() llist1 = linked() llist.push(6) llist.push(4) llist.push(3) llist.push(2) llist.push(1) llist1.push(8) llist1.push(6) llist1.push(4) llist1.push(2) l = linked() print(l.intersect(llist,llist1).data) 

here traceback:

 traceback (most recent call last):   file "c:/users/omsai/desktop/intersection.py", line 48, in <module>     print(l.intersect(llist,llist1).data)   file "c:/users/omsai/desktop/intersection.py", line 26, in intersect     if l2.data>l1.data: attributeerror: 'linked' object has no attribute 'data' 

you're calling linked.intersect 2 instances of linked, doesn't have data member. need actual nodes out in intersect method:

def intersect(self,l1,l2):     l1 = l1.head     l2 = l2.head     dummy = cur = node(0)     # ... 

you don't need call intersect 2 arguments; enough intersect 1 list against another:

def intersect(self, olinked):     thisone = self.head     otherone = olinked.head     retval = linked()     while thisone , otherone:         if otherone.data > thisone.data:             thisone = thisone.next         elif thisone.data > otherone.data:             otherone = otherone.next         else:  # thisone.data == otherone.data             retval.push(otherone.data)             thisone = thisone.next             otherone = otherone.next     return retval  # ...  llist.intersect(llist1).print_list() 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -