import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// 处理空链表(视为回文)
if (head == null) {
return true;
}
// 步骤1:将链表节点的值存入数组
List<Integer> values = new ArrayList<>();
ListNode current = head;
while (current != null) {
values.add(current.val);
current = current.next;
}
// 步骤2:使用双指针判断数组是否为回文
int left = 0;
int right = values.size() - 1;
while (left < right) {
// 若对应位置的值不相等,则不是回文
if (!values.get(left).equals(values.get(right))) {
return false;
}
left++; // 左指针右移
right--; // 右指针左移
}
// 所有对应位置的值都相等,是回文
return true;
}
}