LeetCode

234. Palindrome Linked List

zhelddustmq 2024. 7. 15. 17:32

Given the head of a singly linked list, return true if it is a 

palindrome

 or false otherwise.

 

Example 1:

Input: head = [1,2,2,1]
Output: true

Example 2:

Input: head = [1,2]
Output: false

 

Constraints:

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9

 

Follow up: Could you do it in O(n) time and O(1) space?

 

code by python:

# 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:
        arr = []

        if not head:
            return True

        node = head
        while node:
            arr.append(node.val)
            node = node.next
            
        while len(arr) > 1:
            if arr.pop(0) != arr.pop():
                return False
        
        return True

'LeetCode' 카테고리의 다른 글

704. Binary Search  (0) 2024.07.23
973. K Closest Points to Origin(with. HashTable)  (2) 2024.07.23
200. Number of Islands  (2) 2024.07.16
215. Kth Largest Element in an Array  (0) 2024.07.15
20. Valid Parentheses  (0) 2024.07.12