DEV Community

bengineer
bengineer

Posted on

LeetCode 234: Palindrome Linked List (Ruby)

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

Solution:

def is_palindrome(head)
    return true if !head
    vals = []
    node = head
    loop do
        vals << node.val
        break unless node.next
        node = node.next
    end
    vals == vals.reverse
end
Enter fullscreen mode Exit fullscreen mode

Explanation:

1- Create an empty array

2- Iterate through the linked list and add its values to array created in step 1.

3- Compare the array we created with itself reversed and return.

Top comments (0)