题目:给定一个链表,请判断该链表是否为回文结构。
这个题目不难,但是有几个需要注意的地方。
1. 链表是否为回文结构,是将链表中的元素看作一个整体,不需要对链表中节点内部的值排列进行比较。eg:12->13->13->12,构成回文结构,而不是考虑回文字符串那样按位比较;
2.如果采用List等数据结构,先将链表中的值提取出来再进行判断,则需要注意,判读值相等应该用equals方法,不能再用==,因为此时数据已经是Integer类型的对象了;
3.这题有较多的解法,1)List存储数据,进行判断;2.链表反转后进行判断;3.双端队列数据结构辅助判断等等
我采用的List。
完整代码如下:
public static boolean isPail (ListNode head) {
// write code here
if(head==null||head.next==null) {
return true;
}
List<Integer> temp = new ArrayList<>();
while(head!=null) {
temp.add(head.val);
head = head.next;
}
int i=0,j=temp.size()-1;
while (i<j) {
if(!temp.get(i++).equals(temp.get(j--))) {
return false;
}
}
return true;
}