Easy
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:
[1, 105]
.0 <= Node.val <= 9
Follow up: Could you do it in O(n)
time and O(1)
space?
# Definition for singly-linked list.
#
# defmodule ListNode do
# @type t :: %__MODULE__{
# val: integer,
# next: ListNode.t() | nil
# }
# defstruct val: 0, next: nil
# end
defmodule Solution do
@spec is_palindrome(head :: ListNode.t | nil) :: boolean
def is_palindrome(head) do
reverse(head, nil) == head
end
defp reverse(nil, acc), do: acc
defp reverse(%ListNode{} = node, acc) do
reverse(node.next, %{node | next: acc})
end
end