链表 06. 回文链表

题目:给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。  简单

方法一:栈  时间复杂度O(N)  空间复杂度O(N)

def isPalindrome(head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None or head.next is None:
            return True

        stack = []
        cur = head
        while cur:
            stack.append(cur)
            cur = cur.next
     # 找到链表中点,这样只需要比较一半  但是我就觉得也没省时间 不用也行,不用把下面while的p1 == slow删了就行
        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next

        p1 = head
        while p1 or p1 == slow:
            p2 = stack.pop()
            if p1.val != p2.val:
                return False
            p1 = p1.next
        return True

方法二:反转后半部分链表  时间复杂度O(N)  空间复杂度O(1)

def isPalindrome(head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None or head.next is None:
            return True

        # 找中点
        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next

        # 反转后半部分链表
        half_head = None
        cur = slow
        while cur:
            tmp = cur.next
            cur.next = half_head
            half_head = cur
            cur = tmp
        
        # 判断
        p1 = head
        p2 = half_head
        while p2 and p2.next:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

 

posted @ 2022-07-14 10:30  Liang-ml  阅读(12)  评论(0)    收藏  举报