leetcode234python回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true
第一种方法
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        #复杂度满足要求,空间复杂度为O(n),不满足进阶要求
        if not head:
            return True
        cur=head
        array=[]
        while cur:
            array.append(cur.val)
            cur=cur.next
        return array==array[::-1]

第二种方法,准备直接用链表翻转,然后跟原链表对比,结果出错,还没找到原因



猜你喜欢

转载自blog.csdn.net/it_job/article/details/80482857