この問題の解き方は pointer を2つ使う。
-
真ん中を探す Pointer を2つ使い、fast pointer と fast.next が null になるまで Pinter を進める。 その際 slow pointer が真ん中に位置する。
-
後ろ半分を反転させる slow pointer が真ん中に位置しているので、 slow が null になるまでループさせる。
step.1 1 → 2 → 3 → null
prev と curr を憶えておく必要がある。
prev = null curr = 1
curr の next node を temp に入れておく。 temp = 2
null ← 1 2 → 3 → null
step.2 prev = 1 curr = 2 temp = 3
null ← 1 ← 2 3 → null
step.3 prev = 2 curr = 3 temp = null
null ← 1 ← 2 ← 3 null
step.4 prev = 3 curr = null temp = null
-
左半分と右半分を比べる。 違う場合は、その時点で false を返す。 同じ場合は、left と right を next に移動させて比較していく。
# 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:
fast = head
slow = head
# find middle(slow)
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# reverser second half
prev = None
while slow:
temp = slow.next
slow.next = prev
prev = slow
slow = temp
# check palindrome
left, right = head, prev
while right:
if left.val != right.val:
return False
left = left.next
right = right.next
return True