我正在尝试使用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);
}
}
这是一个计算链表中间位置的函数。我尝试使用python
但它会抛出错误
TypeError:&:'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)
我在这里做错了什么以及解决方案是什么?
答案 0 :(得分:4)
如果需要逻辑和操作,则应编写and
,而不是使用按位和运算符&
。它们具有不同的预测值,因此您的当前代码正在评估,就好像您已编写fast_ptr.next != (None & fast_ptr) != None
一样。这不起作用,因为None & fast_ptr
无效。
您还要按照与C ++代码相反的顺序检查条件的两个部分,这会使and
的短路对您不利(您将尝试)即使fast_ptr.next
本身为fast_ptr
,也要检查None
。尝试将您的条件更改为fast_ptr != None and fast_ptr.next != None
。
请注意,与C ++不同,您不需要围绕Python中while
循环的条件使用括号。您使用None
(或is
)运算符代替is not
(或==
对!=
进行测试也是常规的(尽管不是必需的) })。因此,while
行的更惯用的版本是:
while fast_ptr is not None and fast_ptr.next is not None: