Given the head of a singly linked list, return true if it is a palindrome.
Input: head = [1,2,2,1]
Output: true
Input: head = [1,2]
Output: false
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9
Given the head of a singly linked list, return true if it is a palindrome.
Input: head = [1,2,2,1]
Output: true
Input: head = [1,2]
Output: 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: | |
| # O(n) space, O(n) time complexity | |
| compare_list = [] | |
| while head: | |
| compare_list.append(head.val) | |
| head = head.next | |
| return compare_list[::] == compare_list[::-1] |