LeetCode 234.回文链表

234. 回文链表

Difficulty: 简单

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

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

Solution

Language: ****

# 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
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        y = None
        while slow:
            nxt = slow.next
            slow.next = y
            y = slow
            slow = nxt
            
        while y:
            if y.val != head.val:
                return False
            head = head.next
            y = y.next
            
        return True
posted @ 2020-12-24 22:23  swordspoet  阅读(54)  评论(0编辑  收藏  举报