【问题标题】:How to return the middle node of a linked list如何返回链表的中间节点
【发布时间】:2019-04-16 04:15:35
【问题描述】:

在检查链表的中间节点时,我对 while 循环条件在链表中的工作方式感到困惑

这是我找到链表中间节点的正确代码

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


class linkedList(object):
    def __init__(self):
        self.head = None

    def append(self, data):
        node = Node(data)
        if self.head == None:
            self.head = node
        temp = self.head
        while temp.next:
            temp = temp.next
        temp.next = node

    def middle(self):
        first = self.head
        second = self.head
        while second and second.next:
            second = second.next.next
            first = first.next
        print(first.data)

如果我将 while 循环更改为

while second:

while second.next:

我收到一条错误提示

AttributeError: 'NoneType' object has no attribute 'next' on line 24

我只是想知道为什么同时拥有secondsecond.next 很重要

【问题讨论】:

  • 因为只有当second 有一个有效值时,你才能调用second.next,同样,只有当你有一个有效的second.next 时,你才能调用second.next.next
  • 在下面查看我的答案!

标签: python python-3.x linked-list


【解决方案1】:

该解决方案通过使用两个指针来工作。第一个每次走 1 步,第二步一次走 2 步。但是,在采取 2 个步骤时,需要验证两件事:

  1. 有一个有效的下一步
  2. 在上面提到的下一步之后还有一个步骤

如果你跳过一个检查,它将进入循环,但在边界条件下它找不到下一个。举例说明:如果有 4 个节点并且您只在第 3 个节点检查 second.next,您将拥有 second.next 有效并且您将进入 while 循环,但在其中您直接访问 second.next.next

F,S | 1 --> 2 --> 3 --> 4 --> 无

【讨论】:

    【解决方案2】:

    对于初学者,您的 append 方法不起作用,并且会陷入无限的 while 循环,因为您在添加第一个元素时不会退出 append。正确的版本是

    def append(self, data):
        node = Node(data)
        if self.head == None:
            self.head = node
            return
        else:
            temp = self.head
            while temp.next:
                temp = temp.next
            temp.next = node
    

    关于您的另一个问题,我们希望找到偶数和奇数列表的循环中间,second.next 涵盖奇数列表情况,second 涵盖偶数列表情况,因为第二个指针将指向null,或者它本身将是null,如果你只使用其中一个,你会得到你描述的错误,因此你需要在while循环中同时拥有这两个条件

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2014-10-16
      • 2021-11-06
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      相关资源
      最近更新 更多