思路:遍历链表,把值存入list集合中。使用双指针,判断左右是否相等,不等则返回false。循环结束返回true。
public boolean isPail (ListNode head) {
// write code here
if(head==null){
return false;
}
ArrayList<Integer> list=new ArrayList<Integer>();
ListNode h=head;
while(h!=null){
list.add(h.val);
h=h.next;
}
int l=0;
int r=list.size()-1;
while(l<r){
if(!list.get(l).equals(list.get(r))){//此处我用==,有两个案例不通过。但案例确实不是回文体,我返回的false,答案却是true。
return false;
}
l++;
r--;
}
return true;
}
京公网安备 11010502036488号