这里有用到关于List集合的知识,可看上一篇Java 数组与集合(List, Set, Map)获取长度与遍历操作
解题方法:先将链表存储到动态数组中,然后使用两个指针一头一尾进行遍历操作进行比较
注意:使用equals判断相等,因为链表使用的是Integer类型
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//将链表的值复制到数组中
List<Integer> array=new ArrayList<Integer>();
ListNode p=head;
for(;p!=null;p=p.next){
array.add(p.val);
}
// 双指针法判断
int first=0;
int last=array.size()-1;
while(first<=last){
if(!array.get(first).equals(array.get(last))){
return false;
}
first++;
last--;
}
return true;
}
}