【问题标题】:Linked lists equality exercise in PythonPython中的链表相等练习
【发布时间】:2021-12-09 20:09:48
【问题描述】:

我有以下练习我非常接近解决它但还没有 有人可以提供一些提示吗?

这里是:

假设链表节点是使用具有以下结构的类实现的:

from __future__ import annotations
class Node:
  data : int
  next : Node  #or None

然后给出一个例子

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

node2 = Node(1, None)
node1 = Node(0, node2)
node0 = Node(0, node1)

Node1 = Node(1, None)
Node0 = Node(0, Node1)

assert is_equal(node0, Node0) == False
assert is_equal(node1, Node0) == True

练习也有这段代码你已经完成

from __future__ import annotations

class Node:
     data : int
     next : Node  #or None

def is_equal(head1: Node, head2: Node)-> bool:

这是我的解决方案,但是当我运行自动更正时,它给了我以下错误

self.assertFalse(is_equal(node0, Node0))

我为此获得了通行证

断言 is_equal(node1, Node0) == True

    while head1.data == head2.data:
      
        head1=head1.next
        head2=head2.next
        return True
    else:
      return False

【问题讨论】:

  • 你只检查第一个元素。
  • 好的,但它说 head1 和 head2,我错过了什么?你能详细说明一下吗?
  • 你提前head1,但不是head2。您没有比较相应的节点,只有第一个列表中的每个节点与第二个列表的第一个节点。 (至少,如果您没有在执行 head1 = head1.next 之前立即返回,那么您会这样做。
  • 你需要比较两个节点,然后要么立即返回False或者推进both指针。
  • 我已经更新了代码,并阅读了您的说明,但我仍然收到同样的错误...

标签: python linked-list


【解决方案1】:

您尝试中的一些问题:

  • while 循环将在其第一次迭代中结束,因为它的主体中有无条件的return。所以它实际上并没有循环

  • while 循环无法防止取消引用 None 值,也就是说,在检查 head1.data 之前,您应该首先确保 head1 不是 None

  • 与上一点相关:没有代码处理一个列表比另一个长的情况。

这里是一个更正:

def is_equal(head1: Node, head2: Node)-> bool:
    # Make sure both are node references (not None) before accessing data
    while head1 and head2 and head1.data == head2.data:  
        head1 = head1.next
        head2 = head2.next
    return head1 is head2  # Both must be None for the result to be True

NB:最终的条件可能看起来很奇怪,但是当循环正常结束时,我们知道这两个变量中至少有一个是None,否则它们确实是不同的节点(因为它们有不同的数据),所以通过检查它们是否相同,我们实际上检查它们是否是both None

【讨论】:

    【解决方案2】:

    这是解决方案,问题是比较不同长度的头,因此它们是否返回。

    class Node:
      def __init__(self, Data, Next):
        (self.data, self.next) = (Data, Next)
    
     
    def is_equal(head1: Node, head2: Node)-> bool:
    
        while head1 != None and head2 != None and head1.data == head2.data:
          
            head1=head1.next
            head2=head2.next
            
        if head1 != None or head2 !=None:
          return False
        else:
          return True
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      相关资源
      最近更新 更多