& 不支持的操作数类型:“NoneType”和“Node”

BOT*_*Jr. 1 python

我正在尝试使用 来实现链表Python。因为,我是新手python,所以我通过编写一些我可以在C++.

  /* Function to get the middle of the linked list*/
void printMiddle(struct Node *head)
{
    struct Node *slow_ptr = head;
    struct Node *fast_ptr = head;

    if (head!=NULL)
    {
        while (fast_ptr != NULL && fast_ptr->next != NULL)
        {
            fast_ptr = fast_ptr->next->next;
            slow_ptr = slow_ptr->next;
        }
        printf("The middle element is [%d]\n\n", slow_ptr->data);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个计算链表中间的函数。我尝试了相同的操作,python但它抛出了一个错误

类型错误:& 不支持的操作数类型:“NoneType”和“Node”

 def middle_node(self):
        slow_ptr=self.head
        fast_ptr=self.head
        if self.head==None:
            return

        while (fast_ptr.next!=None & fast_ptr!=None):
            fast_ptr=(fast_ptr.next).next
            slow_ptr=slow_ptr.next
        print (slow_ptr.data)
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么以及解决方案是什么?

Blc*_*ght 5

当您需要逻辑与运算时,您应该编写and,而不是使用按位与运算符&。它们具有不同的优先级,因此您当前的代码正在被评估,就好像您编写了fast_ptr.next != (None & fast_ptr) != None. 这不起作用,因为None & fast_ptr无效。

您还以与 C++ 代码相反的顺序检查条件的两个部分,这使得 not 的短路and对您有利(fast_ptr.next即使fast_ptrisNone本身,您也会尝试检查)。尝试将您的条件更改为fast_ptr != None and fast_ptr.next != None.

请注意,与 C++ 不同,Python 中的循环条件不需要括号whileNone使用is(or is not) 运算符而不是==(or )进行测试也是传统的(尽管不是必需的)!=。所以你的行的更惯用的版本while是:

while fast_ptr is not None and fast_ptr.next is not None:
Run Code Online (Sandbox Code Playgroud)