ExamAdda Logo

Palindrome Linked List

Easy

Given the head of a singly linked list, determine whether the linked list is a palindrome.

A linked list is a palindrome if its values read the same forward and backward.

Return true if the linked list is a palindrome, otherwise return false.

Example 1

Input

n = 4
head = [1, 2, 2, 1]

Output

true

Explanation

Reading the list from both directions gives:

1 2 2 1
1 2 2 1

Both are the same, so the linked list is a palindrome.

Example 2

Input

n = 2
head = [1, 2]

Output

false

Explanation

The list reads differently in the two directions:

1 2
2 1

Therefore, it is not a palindrome.

Constraints

1 <= n <= 10^5
-10^5 <= Node.val <= 10^5
The linked list contains at least one node.

Hints:

Hint 1

Find the middle of the linked list using slow and fast pointers.

Hint 2

Reverse the second half of the linked list.

Auto
Loading editor...
Input

Expected Output