LeetCode-in-All

234. Palindrome Linked List

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:

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

Solution

%% Definition for singly-linked list.
%%
%% -record(list_node, {val = 0 :: integer(),
%%                     next = null :: 'null' | #list_node{}}).

-spec is_palindrome(Head :: #list_node{} | null) -> boolean().
-import(lists,[reverse/1]). 

list_to_seq(null) -> [];
list_to_seq(Head) ->
    [Head#list_node.val] ++ list_to_seq(Head#list_node.next).

is_palindrome(null) -> false;
is_palindrome(Head) ->
    Seq = list_to_seq(Head),
    Seq =:= reverse(Seq).