将值复制到数组中后用双指针法
时间复杂度O(n)
class Solution {
public boolean isPalindrome(ListNode head) {
ArrayList<Integer> a1 = new ArrayList<Integer>();
while(head != null)
{
a1.add(head.val);
head = head.next;
}
int n = a1.size()-1;
for(int i = 0; i<a1.size()/2; i++)
{
System.out.println("a1.get(i):"+a1.get(i));
System.out.println("a1.get(--n):"+a1.get(n));
if(a1.get(i) != a1.get(n))
{
return false;}
n--;
}
return true;
}
}
官方
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<Integer>();
// 将链表的值复制到数组中
ListNode currentNode = head;
while (currentNode != null) {
vals.add(currentNode.val);
currentNode = currentNode.next;
}
// 使用双指针判断是否回文
int front = 0;
int back = vals.size() - 1;
while (front < back) {
if (!vals.get(front).equals(vals.get(back))) {
return false;
}
front++;
back--;
}
return true;
}
}