实现合并排序[AttributeError:'int'对象没有属性'data'时出错]

2024-09-28 03:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python中合并两个已排序的链表,但在执行一半后,获取AttributeError:“int”对象没有属性“data”错误。请帮帮我,因为我没有弄错我在做什么。 因为它正在执行前3个值,但是它给出了错误

class Node:
  def __init__(self,data):
    self.data=data
    self.next=None

def printList(head):
    temp=head
    while temp:
      print(temp.data,end=' ')
      temp=temp.next
    print()

def mergeList(head1,head2):
    temp1=head1
    temp2=head2
    i=0
    j=0

    while i<3 and j<4:
      if temp1.data<=temp2.data:
        print(temp1.data,end=' ')
        temp1=temp1.next
        i+=1
      else:
        print(temp2.data,end=' ')
        temp2=temp2.data
        j+=1

    while i<3:
      print(temp1.data,end=' ')
      temp1=temp1.next
      i+=1

    while j<4:
      print(temp2.data,end=' ')
      temp2=temp2.data
      j+=1


if __name__=='__main__':

  first=Node(1)
  second=Node(3)
  third=Node(5)
  head1=first
  first.next=second
  second.next=third
  
  first2=Node(3)
  head2=first2
  second2=Node(4)
  third2=Node(5)
  fourth2=Node(6)
  first2.next=second2
  second2.next=third2
  third2.next=fourth2


  printList(head1)
  printList(head2)
  mergeList(head1,head2)

这是我得到的输出

1 3 5 
3 4 5 6 
1 3 3 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-27-fcaa90b70961> in <module>()
     59   printList(head1)
     60   printList(head2)
---> 61   mergeList(head1,head2)
     62 
     63 

<ipython-input-27-fcaa90b70961> in mergeList(head1, head2)
     18 
     19     while i<3 and j<4:
---> 20       if temp1.data<=temp2.data:
     21         print(temp1.data,end=' ')
     22         temp1=temp1.next

AttributeError: 'int' object has no attribute 'data'

Tags: nodedatadeftempnextendattributeerrorprint
2条回答

看来你很接近得到正确的输出。我在那些破坏代码的行以及应该如何替换代码的行中添加了注释

while i < 3 and j < 4:
    if temp1.data <= temp2.data:
        print(temp1.data, end=' ')
        temp1 = temp1.next
        i += 1
    else:
        print(temp2.data, end=' ')
        temp2 = temp2.data  # <   this should be .next
        j += 1

while i < 3:
    print(temp1.data, end=' ')
    temp1 = temp1.next
    i += 1

while j < 4:
    print(temp2.data, end=' ')
    temp2 = temp2.data   # <   this should be .next
    j += 1

您正在为temp2分配一个整数值,而在接下来的迭代中仍将其视为Node。将.data更改为.next将使代码产生以下结果:

1 3 5 
3 4 5 6 
1 3 3 4 5 5 6 
Process finished with exit code 0

这种方法也给出了正确的答案

def mergeList(head1,head2):
    temp1=head1
    temp2=head2
    
    while temp1 and temp2:
      if temp1.data<=temp2.data:
        print(temp1.data,end=' ')
        temp1=temp1.next
      else:
        print(temp2.data,end=' ')
        temp2=temp2.next

    while temp1:
      print(temp1.data,end=' ')
      temp1=temp1.next

    while temp2:
      print(temp2.data,end=' ')
      temp2=temp2.next

相关问题 更多 >

    热门问题