LeetCode 234 回文表

题目

请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false

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

思路

  1. 利用双指针找到链表的中间位置
    每一次慢指针移动一步,快指针移动两步,当快指针遍历到链表最后的时候,慢指针正好指向链表中间节点
  2. 将后半部分链表反转
  3. 反转后,遍历比较前半段和后半段链表,主要终止条件

代码

class Solution(object):
    def isPalindrome(self, head):
        if head == None or head.next == None:
            return True
        slow = head
        fast = head
        while fast and fast.next: # 注意终止条件
            slow = slow.next
            fast = fast.next.next

        mid = slow # 找到链表的中间节点
        new_head = None
        while mid: # 将后半段链表反转
            nxt = mid.next
            mid.next = new_head
            new_head.next = mid
            mid = nxt

        while head != slow: # 判断是否是回文表
            if head.val == new_head.val:
                head = head.next
                new_head = new_head.next
            else:
                return False
        return True
    

你可能感兴趣的:(LeetCode 234 回文表)