美文网首页
链表 Leetcode 234 回文链表

链表 Leetcode 234 回文链表

作者: 禾木清清 | 来源:发表于2019-07-15 19:43 被阅读0次

题目

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

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

本题要求回文链表,并且要求了空间复杂度O(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
        """
        if not head or not head.next:
            return True
        
        slow = fast = head 
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        
        slow = slow.next
        slow = self.reverse(slow)
        
        while slow:
            if slow.val != head.val:
                return False
            slow = slow.next
            head = head.next
        return True
        
    def reverse(self,head):
        temp = curr = None
        # head 

        while head:
            curr = head
            head = head.next
            curr.next = temp
            temp = curr
        return curr 

相关文章

网友评论

      本文标题:链表 Leetcode 234 回文链表

      本文链接:https://www.haomeiwen.com/subject/gouokctx.html