(Python)求两个链表的和,其中每个节点都是一个整数.属性错误


class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class LinkedList:
def __init__(self, node = None):
self.head = node
self.length = 0

def InsertNode(self, data):
newNode = Node()
newNode.data = data
if self.length == 0:
self.head = newNode
else:
newNode.next = self.head
self.head = newNode
self.length += 1

def printList(self):
temp = self.head
while temp != None:
print(temp.data, end = " ")
temp = temp.next

class AddingListNumbers:
def addTwoNumbers(self, list1, list2):
if list1 == None:
return list2
if list2 == None:
return list1
len1 = len2 = 0
head = list1.head
while head != None:
len1 += 1
head = head.next
head = list2.head
while head != None:
len2 += 1
head = head.next
if len1 > len2:
shorter = list2
longer = list1
else:
shorter = list1
longer = list2
sum = None
carry = 0
while shorter != None:
value = shorter.data + longer.data + carry
carry = value / 10
value -= carry * 10
if sum == None:
sum = Node(value)
result = sum
else:
sum.next = Node(value)
sum = sum.next
shorter = shorter.next
longer = longer.next
while longer != None:
value = longer.data + carry
carry = value / 10
value -= carry * 10
sum.next = Node(value)
sum = sum.next
longer = longer.next
if carry != 0:
sum.next = Node(carry)
return result
linkedlist = LinkedList()
linkedlist.InsertNode(19)
linkedlist.InsertNode(14)
linkedlist.InsertNode(11)
linkedlist.InsertNode(9)
linkedlist.InsertNode(6)
linkedlist.InsertNode(5)
linkedlist2 = LinkedList()
linkedlist2.InsertNode(17)
linkedlist2.InsertNode(16)
linkedlist2.InsertNode(13)
linkedlist2.InsertNode(6)
linkedlist2.InsertNode(2)
linkedlist2.InsertNode(1)
linkedlist2.InsertNode(24)
linkedlist2.InsertNode(3)
linkedlist2.InsertNode(11)
list3 = LinkedList()
ResultList = AddingListNumbers()
list3.next = ResultList.addTwoNumbers(linkedlist, linkedlist2)
list3.printList()

我创建了Node和LinkedList类,然后创建了另一个类AddingListNumbers来添加列表号。我收到一条错误消息:

value=shorter.data+longer.data+进位AttributeError:"LinkedList"对象没有属性"data">

我不知道如何调试这个。如何处理属性错误?

下面是错误消息的图片

问题出在这个部分:

if len1 > len2:
shorter = list2 # should be list2.head instead
longer = list1 # should be list1.head instead
else:
shorter = list1 # should be list1.head instead
longer = list2 # should be list2.head instead

不过,话虽如此,该代码可以优化为只遍历列表一次。在这个实现中,您首先要查找较短的列表,然后在遍历较短列表时添加。它可以在单个遍历中完成为:

  1. 在遍历list1或完全遍历list2时重复这些步骤
  2. 从列表1的节点添加数据(如果存在(,或添加0
  3. 从列表2的节点添加数据(如果存在(,或添加0
  4. 把进位加到上面的和上
  5. 计算和的divmod,并重新分配进位和和
  6. 如果存在下一个节点,则向前移动指针

结果列表将包含列表的总和。

最新更新