6Luffy6

导航

234. 回文链表

  1. 回文链表

传送锚点234. 回文链表 - 力扣(LeetCode)

给你一个单链表的头节点 head ,请你判断该链表是否为

回文链表

。如果是,返回 true ;否则,返回 false

示例 1:

输入:head = [1,2,2,1]
输出:true

示例 2:

输入:head = [1,2]
输出:false

提示:

  • 链表中节点数目在范围[1, 105]
  • 0 <= Node.val <= 9

思路

找到链表的中间节点 ,求链表长度,若为奇数,中间节点再往后移,在将中间节点以后一段链表翻转,最后遍历链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    #z找到中间节点
    def middle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow
    
    #求链表长度
    def length(self, head: Optional[ListNode]) -> int:
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next 
        return n
    
    #将链表翻转
    def reverse(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = None
        cur = head
        while cur:
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt
        return pre
	
    
    
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        n = self.length(head)
        head2 = self.middle(head)
        #如果链表长度为奇数 则head2往后移
        if(n & 1):
            head2 = head2.next

        head2 = self.reverse(head2)        
        while head2:
            if head.val != head2.val:
                return False
            head = head.next
            head2 = head2.next
        return True


       

posted on 2024-08-27 22:52  不AC不睡觉  阅读(1)  评论(0编辑  收藏  举报