回文链表,代码未通过测试用例

2024-04-28 05:33:26 发布

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

这是我的密码:

    if head and head.next is None:
        return True
    current = head
    prev = None
    nex = None
    while current:
        nex = current.next
        current.next = prev
        prev = current
        current = nex
    while head:
        head = head.next
    if prev == head:
        return True
    else:
        return False

代码做两件事

1:它反转链表

2:检查当前链表是否等于反向链表

然而,这只通过了26个测试用例中的17个。 让我感到困惑的是它不能通过这个测试用例[ 0,0 ]

我错过了什么?不是0==0吗

这是我从其他人提交的文件中复制的第二个代码,我们的想法是相同的

逆转 检查是否相等

        sol = []
        current = head
        while current:
            sol.append(current.val)
            current = current.next
        return sol == sol[::-1]

这段代码运行良好

那么有什么区别呢?我错过了什么


Tags: 代码nonetrue密码returnif测试用例current