leetcode--python--234

234. Palindrome Linked List

Please determine whether a linked list is a palindrome linked list

Caiji can only speed and slow pointers. Recursion is really difficult. If you don’t understand,
you can also create an array, put the values ​​in the linked list into the array, and then just do it, but because an array containing all the linked list values ​​is created, Space complexity becomes O(n)

# 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:
        if head == None:
            return(True)
        
        fast, slow = head, head
        while fast.next and fast.next.next:#注意这个判定条件
            fast = fast.next.next
            slow = slow.next
        
        #通过上面的得到了指向中点的slow指针,下面就是通过slow反转链表了
        cur = slow.next
        pre = None
        while cur:
            tem = cur.next
            cur.next = pre
            pre = cur
            cur = tem
        #返回的pre就是反转后的链表,只需要逐个判定对应节点的值是否相等就行
        while pre:
            if pre.val != head.val:
                return(False)
            else:
                pre = pre.next
                head = head.next
        return(True)

Time complexity: Find the intermediate node O(n/2), reverse the linked list O(n/2), judge whether the value of the corresponding position of the reverse linked list and the original linked list are equal O(n/2), so the final total time is complicated Degree O(n)
space complexity: Since only a few pointers are created temporarily, the space complexity is O(1)

Guess you like

Origin blog.csdn.net/AWhiteDongDong/article/details/111403064
234