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.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
class Solution {
bool isPalindrome(ListNode? head) {
List<int> list = [];
while (head != null) {
list.add(head.val);
head = head.next;
}
int l = 0;
int r = list.length - 1;
while (l < list.length && r >= 0 && list[l] == list[r]) {
l++;
r--;
}
return l == list.length;
}
}