问题描述
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
解决办法
- 定义两个指针 slow 和 fast,只要fast 向后的两个节点存在,那么,slow 每次向后移动一个节点,fast 每次向后移动两个节点。
- 最终移动完成后会将链表分为两部分,当链表的节点数为偶数时,slow 指向前半个链表的最后一个节点;当链表节点数为奇数时,slow 指向中间节点。fast 则指向后半个链表的最后一个节点。
def half(self,head):
slow,fast = head,head
while fast.next is not None and fast.next.next is not None:
slow=slow.next
fast=fast.next.next
return slow
- 将后半段链表进行反转,即得到以 fast 为头结点的新链表
def reverse(self,head):
pre=None
cur=head
while cur is not None:
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return pre
- 最后对前半段链表和后半段链表进行比较,若相等,则为回文,返回 True;若不等,则返回 False。
完整代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if head is None:
return True
pre_half=self.half(head)
sec_half=self.reverse(pre_half.next)
result=True
first=head
second=sec_half
while result and second is not None:
if first.val != second.val:
return False
first=first.next
second=second.next
return result
def half(self,head):
slow,fast = head,head
while fast.next is not None and fast.next.next is not None:
slow=slow.next
fast=fast.next.next
return slow
def reverse(self,head):
pre=None
cur=head
while cur is not None:
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return pre
测试结果: