【问题标题】:Intersection of two sorted Linked lists in python3?python3中两个排序链表的交集?
【发布时间】:2017-08-18 12:19:37
【问题描述】:

我的代码无法两次打印出作为两个排序链表交集的新列表。它无法访问函数内部的列表。请指出我代码中的错误。我的代码中没有缩进问题,算法似乎也很好。

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 and 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)

这是回溯:

 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'

【问题讨论】:

    标签: python algorithm python-3.x data-structures linked-list


    【解决方案1】:

    您使用两个 Linked 实例调用 Linked.intersect,而这两个实例没有 data 成员。您需要在intersect 方法中取出实际节点:

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

    您可能不需要使用两个参数调用intersect;将一个列表与另一个列表相交就足够了:

    def intersect(self, olinked):
        thisone = self.head
        otherone = olinked.head
        retval = Linked()
        while thisone and 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()
    

    【讨论】:

    • 它现在显示以下错误:Traceback(最近一次调用最后一次):文件“C:/Users/omsai/Desktop/intersection.py”,第 51 行,在 print(l .intersect(llist,llist1).data) 文件“C:/Users/omsai/Desktop/intersection.py”,第 33 行,在 intersect cur.next = l1.data AttributeError: 'NoneType' 对象没有属性 'next'
    • 感谢您的帮助。有效。好像在leetcode上解决问题和自己的编辑器完全不一样
    猜你喜欢
    • 1970-01-01
    • 2015-12-30
    • 2011-01-24
    • 1970-01-01
    • 2015-10-17
    • 2019-07-26
    • 1970-01-01
    • 2019-03-16
    • 2011-01-21
    相关资源
    最近更新 更多