class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def is_palindrome(head: ListNode) -> bool:
    if not head or not head.next:
        return True
    
    # الخطوة 1: إيجاد منتصف القائمة
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    # الخطوة 2: عكس النصف الثاني من القائمة
    prev = None
    while slow:
        temp = slow.next
        slow.next = prev
        prev = slow
        slow = temp
    
    # الخطوة 3: مقارنة النصف الأول مع النصف الثاني المعكوس
    first_half, second_half = head, prev
    while second_half:  # نحتاج فقط للمقارنة مع النصف المعكوس
        if first_half.val != second_half.val:
            return False
        first_half = first_half.next
        second_half = second_half.next
    
    return True

# مثال للاختبار
# إنشاء القائمة المرتبطة [1,2,2,1]
head = ListNode(1, ListNode(2, ListNode(2, ListNode(1))))

# تطبيق دالة التحقق من palindrome
result = is_palindrome(head)

print(result)  # يجب أن تطبع True
