Soohan-Kim / Leetcode

0 stars 0 forks source link

[HW 3] Palindrome Linked List #234. #28

Open Soohan-Kim opened 3 months ago

Soohan-Kim commented 3 months ago

https://leetcode.com/problems/palindrome-linked-list/description/

Soohan-Kim commented 3 months ago
# 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:
        lenList = 0
        cur = head
        while cur:
            cur = cur.next
            lenList += 1
        half = lenList // 2

        prev = None
        for _ in range(half):
            nxt = head.next
            head.next = prev
            prev = head
            head = nxt

        if lenList % 2:
            head = head.next

        while prev:
            if prev.val != head.val:
                return False
            head = head.next
            prev = prev.next

        return True