简体   繁体   中英

can someone tell me why this is wrong?

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        
        if head == self.reverse(head):
            return True
        return False
        
    
    def reverse(self, head):
        if not head or not head.next:
            return head
        
        cur = head
        prev = None
        
        while cur:
            tmp = cur.next
            cur.next = prev
            
            prev = cur
            cur = tmp
            
        return prev

on the testcase [0, 0], the outcome will be false, but for others the outcomes are correct. This is leetcode234.

It looks like your solution's overall idea is to reverse the linked list and compare it to see if it's equal to the original linked list.

One problem, then, is that although your solution's reverse method looks like it correctly reverses a linked list, it's destructive : because it changes all the node pointers, the original linked list is gone by the time it returns. After it returns, you'll have a reversed linked list, but you won't have the original linked list to compare it against any more! One way to fix this could be to create and return a new linked list that's the reversal of the linked list you passed into reverse .

Assuming you fix that, the second problem is that (unless LeetCode does more behind the scenes than it's mentioning here) == won't do anything useful between two ListNode s, because it just calls the __eq__ method on the class, which nobody has defined. If you want to check if two linked lists are equal in the sense that they have all the same values in the same order, you may have to define your own method or function to do it node by node, value by value.

Not sure where we are checking for palindromeness in your code.

For this problem we can simply iterate through and return using A == A[::-1] to check for palindrome (in Python):

class Solution:
    def isPalindrome(self, head):
        vals = []
        while head:
            vals.append(head.val)
            head = head.next
        return vals == vals[::-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM