234. 回文链表

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

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

 

无脑法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

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

 

 数学法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        s1=0
        s2=0
        t=1

        while head:
            s1=s1*10+head.val
            s2=s2+t*head.val
            t=t*10
            head=head.next
            
        return s1==s2

 

 双指针

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        slow=fast=head
        pre=None
        while fast:
            slow=slow.next
            fast=fast.next.next if fast.next else fast.next
        while slow:
            tmp=slow.next
            slow.next=pre
            pre=slow
            slow=tmp
        while head and pre:
            if head.val!=pre.val:
                return False
            head=head.next
            pre=pre.next
        return True

 

posted @ 2020-10-04 17:53  XXXSANS  阅读(118)  评论(0编辑  收藏  举报