[List] Leetcode palindromic list (234)

topic

Make a list to determine whether the list is a palindrome.

Example 1:

输入: 1->2
输出: false

Example 2:

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

Advanced:
You can use O (n) time complexity and O (1) space complexity to solve this problem?

answer

Two ways:

  • Traversing the linked list, an array stored-value, and then compared. Time complexity of O (n), the spatial complexity of O (n)
  • Finger: Find the midpoint, reversing a linked list after the midpoint, then compare. Time complexity of O (n), the spatial complexity is O (1)

By code is as follows:

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

class Solution:
    # # 改为数组:时间复杂度O(n),空间复杂度O(n)
    # def isPalindrome(self, head: ListNode) -> bool:
    #     l = []
    #     while head:
    #         l.append(head.val)
    #         head = head.next
    #     return l == l[::-1]


    # 指针法:时间复杂度O(n),空间复杂度O(1)。找到中点,反转中点之后的链表,再比较
    def isPalindrome(self, head: ListNode) -> bool:
        if not head or not head.next:
            return True
        # 找到中点,快指针走的路程是慢的两倍,快指针结束慢指针刚好在中间
        f = s = head
        while f:
            s = s.next
            f = f.next.next if f.next else f.next
        
        # 反转中点之后的链表,1->2->0->2->1 ————》 1->2->0<-2<-1
        c, p = s, None
        while c:
            n = c.next
            c.next = p
            p = c
            c = n
        
        # 相对比较
        while p:
            if head.val != p.val:
                return False
            head = head.next
            p = p.next
        return True

Guess you like

Origin www.cnblogs.com/ldy-miss/p/11934467.html